I'm trying to display an error, generated by the back-end, in the front-end developed in Angular material. I want that the error message is displayed into an alert window. My problem is that the error message is displayed only in the console, while the message displayed in the alert window is "undefined". How can I deal with this problem?
service.ts:
export class UserService {
constructor(private http: HttpClient) { }
public createUser(user: User): Observable<User> {
return this.http.post<User>('http://localhost:8080/users/reg', user)
.pipe(
catchError(this.handleError)
);;
}
private handleError(error: HttpErrorResponse) {
if (error.status === 0) {
// A client-side or network error occurred.
console.error('An error occurred:', error.error);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(
`Backend returned code ${error.status}, body was: `, error.error);
}
return throwError(
'Something bad happened; please try again later.');
}
}
component.ts:
public createUser(message: string, action: string, createForm:NgForm ) {
this.userService.createUser(createForm.value).subscribe(
(response: User) => {
this.user=response;
console.log(response);
console.log(createForm.value);
this._snackBar.open(message, action);
createForm.reset();
},
(error: HttpErrorResponse)=>{
alert(error.message);
createForm.reset();
}
)
}
The following is the screenshot of the console which displays the message error that I want to show in the alert window:
When I change alert(error.message)
with console.error('foo', error);
the console says:
In the method "handleError", you are returning a string:
return throwError(
'Something bad happened; please try again later.');
So, when you subscribe, you'll receive the string 'Something bad happened; please try again later.'
If you want the subscriber to receive the message, change your handleMessage return value:
return throwError(error);