angularobservableangular-observableangular-errorhandler

can't display backend errors in component html - Angular


I'm trying to display the backend error that I generate with my errorHandler, but it's not showing anything.

How can I show it?

it returns undefined

HTML

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

    {{ backendError}}

COMPONENT TS

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

SERVICE TS The console log in getErrors() gives me 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 The console log get printed

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.');
}

Solution

  • You need to do something like:

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

    So that your handleError method does not lose the context of the service it is defined in.