Reputation: 1304
I have an Angular application which consists of a form and a submit button. When I fill the form and submit it, if the database injection operation was successful, I want it to return a success message and right after clean the form. To do that, I made us of the subscribe
method, however, the code never goes inside this method and the desired functionalities are not triggered.
insertRecord(form : NgForm){
this.service.postAsset(form.value).subscribe(res =>{
this.toastr.success('Inserted succesfull', 'Asset Register');
this.resetForm(form);
});
}
The postAsset
method is working succesfully and the value is added to the database table, however subscribe
method is never working. Whay may be causing this? Any help is appreciated.
Edit: As it requested, the postAsset()
implementation;
postAsset(formData: Asset){
return this.http.post(this.rootURL + '/Create', formData);
}
Edit 2: The error occurs a few seconds after submitting the form;
SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:13804:51)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2781:31)
at Object.onInvokeTask (http://localhost:4200/vendor.js:59285:33)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2780:60)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2553:47)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2856:34)
at invokeTask (http://localhost:4200/polyfills.js:4102:14)
at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:4139:21)
Upvotes: 0
Views: 74
Reputation: 536
You can try changing your code as below:
postAsset(formData: Asset){
return this.http.post(this.rootURL + '/Create', formData)
.pipe(
map((response: any)
return response;
)
);
}
Add below line at top
import { map } from 'rxjs/operators';
Upvotes: 0
Reputation: 38757
Please trying adding option of {responseType: 'text'}
to your HttpClient POST request:
postAsset(formData: Asset) {
return this.http.post(this.rootURL + '/Create', formData, { responseType: 'text' });
}
This is mentioned in the HttpClient documentation under Requesting non-JSON data.
What seems to be happening with your request is that the server is returning something other than type application/json
. HttpClient attempts by default to effectively do JSON.parse()
behind the scenes unless you specify a different type. Trying to do JSON.parse()
on a non-JSON string would cause the error you are experiencing.
I'd recommend to always return type of application/json
if possible from your server to avoid needing to do this.
Hopefully that helps!
Upvotes: 1