我试图在使用 Angular 材料开发的前端中显示由后端生成的错误。我希望错误消息显示在警报窗口中。我的问题是错误消息仅显示在控制台中,而警报窗口中显示的消息是“未定义”。我该如何处理这个问题?
服务.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.');
}
}
组件.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();
}
)
}
以下是控制台的屏幕截图,它显示了我想在警报窗口中显示的消息错误:
当我alert(error.message)
用console.error('foo', error);
控制台改变时说: