In an Angular 8 app I have the following method:
onSubmit() {
this.mailService.sendMessage().subscribe(
(res: any) => {
this.toastr.success('Message Sent');
this.resetForm();
},
err => {
this.toastr.error('Message Not Sent', res.status);
}
);
}
The sendMessage()
function is in a Service component and is as follows:
sendMessage(){
return this.http.post(environment.apiEndpoint + environment.messageController, this.mailMessage);
}
http
being a HttpClient
object from @angular/common/http
.
Incredibly res
is always skipped, no matter the success or failure of the server comunication, in fact that res.status
you see in the err
lambda prints 200 which is the code for a successfull transaction with the server, I already had checked that but printed it nonetheless, just to make sure.
Adding to that, the post is successfully received and managed by the server as is to be expected by the 200 OK response.
Can Someone tell me what's going on here? Why is res
being seemingly ignored?
Your code is incomplete. You need to map the result. Something like this
import { catchError, map } from 'rxjs/operators';
sendMessage(){
return this.http.post(environment.apiEndpoint +
environment.messageController, this.mailMessage).pipe(
map((result) => result), catchError(err => throwError(err))
)
};
This transforms success result.
Note: If your application doesn't have global error handling. You need to catch the error!
It may be that your backend is responding error with the status code 200. Check the server to make sure.