Reputation: 2329
I want to show message returned by the API which status is 404 as below:
{message: "Email Address does not exists", status: 404, data: null}
This API is generated in SpringBoot language.
I'm calling the API in Angular 8 through a service.ts
file:
forgotPwd(value, bearer) {
return this.http.put(this.rootUrl + 'api/user/forgot_password', value, {headers: new HttpHeaders({ Authorization: 'Bearer ' + bearer, 'Content-Type': 'application/json'})});
}
And in the component.ts
file, I want to handle the situation like:
this.commService.forgotPwd(this.submissionArray, this.userToken).subscribe((data: any) => {
this.rawData = data;
const result = this.rawData;
if (result.status !== 200) {
console.log(result.message);
} else {
console.log(result.message);
}
});
However, I did not see anything in the console. How can handle 404 / 400 request in Angular and can throw corresponding message in the component file as mentioned above?
Upvotes: 0
Views: 500
Reputation: 872
All the http errors will be available in the error callback, for example
this.service.getData()
.subscribe(
(data) => {}, // success path
(error: HttpErrorResponse)=> {} // error path
);
In the error, you will get the status and message.
So for your case,
this.commService.forgotPwd(this.submissionArray, this.userToken)
.subscribe((data: any) => {
this.rawData = data;
const result = this.rawData;
console.log(result.message);
}, error => {
console.log('handle error');
});
Note: The above scenario works, when the Rest API returns 4XX or 5XX as response status.
Upvotes: 2