繁体   English   中英

如何在 Angular 的前端显示后端错误?

[英]How do I display a back-end error in the front-end in Angular?

我试图在使用 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.');
  }


}

在方法“handleError”中,您将返回一个字符串:

return throwError(
      'Something bad happened; please try again later.');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM