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