无法在组件 html - Angular 中显示后端错误

can't display backend errors in component html - Angular

我正在尝试显示我使用 errorHandler 生成的后端错误,但它没有显示任何内容。

如何显示?

它returnsundefined

HTML

 //This triggers the observable, if it has an error it sets that error to the variable backendError 
    {{(pickupAvailabilityList$ | async)}} 

    {{ backendError}}

组件 TS

getPickupAvailability(
    equipmentLookup: EquipmentID[]
  ): Observable<PickupAvailability[]> {
    this.backendError = this.pickupAvailabilityService.getErrorMessage();
    return this.pickupAvailabilityService.getAmountDue(equipmentLookup);
}

SERVICE TS 控制台登录 getErrors() 给我 undefined

getAmountDue(equipmentID: EquipmentID[]): Observable<PickupAvailability[]> {
    this.errorHandler.errorMessages = '';
    return this.http
      .post<PickupAvailability>(
        this.BASE_URL + this.AMOUNT_DUE_URL,
        equipmentID
      )
      .pipe(catchError(this.errorHandler.handleError));
  }

  getErrorMessage(): string {
    this.errorMessage = this.errorHandler.errorMessages;
    return this.errorHandler.errorMessages;
}

ERROR HANDLER SERVICE TS 打印控制台日志

handleError(error: HttpErrorResponse) {
    // To know the version of RxJS npm list --depth=0
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred: ', error.error.message);
      this.errorMessages =
        error.error.message;
    } 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.message}`
      );
      this.errorMessages =
        `Backend returned code ${error.status}` + ` body was: ${error.message}`;
    }
    // return an observable with a user-facing error message
    return _throw('Something bad happened; please try again later.');
}

您需要执行以下操作:

 .pipe(catchError((err,caught)=>{
     return this.errorHandler.handleError();
  }));

这样您的 handleError 方法就不会丢失定义它的服务的上下文。