1

We are trying to see how can we do error handling using the async pipe. We know how to do it if we subscribe to the http GET request, but we aren't subscribing to it. Do I have to do it using .pipe?

TS

getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
    return this.http.post<PickupAvailability>(
      this.BASE_URL + this.AMOUNT_DUE_URL,
      equipment
    );

HTML

{{ testAmountDue$ | async }}
2
  • 1
    have you checked out the docs? angular.io/guide/http#error-handling is there something in particular you are looking for? pipe is one way to go, interceptor is another... just not sure what you're looking to do. Commented Aug 22, 2018 at 21:28
  • @AndyDangerGagne OMG there are so many. I guess for this simple POST request I will end using pipes. Thanks tho! Commented Aug 22, 2018 at 23:52

1 Answer 1

2

I decided to answer my own question since I found the solution,to solve my problem I decided to use the .pipe solution based on this POST request being a very simple request.

First we write an error handler like the following:

TS- pickup-availability.service.ts

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', 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.error}`);
  }
  // return an observable with a user-facing error message
  return throwError(
    'Something bad happened; please try again later.');
};

Notice that this handler returns an RxJS ErrorObservable with a user-friendly error message. Consumers of the service expect service methods to return an Observable of some kind, even a "bad" one.

Now you take the Observables returned by the HttpClient methods and pipe them through to the error handler.

TS- pickup-availability.service.ts

 getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
        return this.http.post<PickupAvailability>(
          this.BASE_URL + this.AMOUNT_DUE_URL,
          equipment
        ).pipe(
      catchError(this.handleError)
    );
 }

Source: https://angular.io/guide/http#error-handling

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.