0

我试图在使用 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);控制台改变时说:

在此处输入图像描述

4

1 回答 1

1

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

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

因此,当您订阅时,您将收到字符串'Something bad happened; please try again later.'

如果您希望订阅者接收消息,请更改您的 handleMessage 返回值:

return throwError(error);
于 2022-02-06T16:37:11.903 回答