I have service level error handling for my API requests. This works great except I want to be able to notify users that something went wrong on the UI other than just the console messages. I figured Material Snackbars would be great for this.
After doing some research it looks like the Angular HttpClient runs outside of the zone, so I wrapped my snackbar.open() method like so to solve the issue:
//POST METHOD
///////////////////////////////////////////////////////////////////////////
addNewCategory(category: CreateCategory): Observable<CreateCategory> {
return this.http
.post<CreateCategory>(this.url + "/create", category)
.pipe(catchError(this.handleError));
}
//ERROR HANDLING METHOD
///////////////////////////////////////////////////////////////////////////
private handleError(errorResponse: HttpErrorResponse) {
if (errorResponse.error instanceof ErrorEvent) {
console.log("Client Side Error: ", errorResponse.error.message);
} else {
console.log("Server Side Error: ", errorResponse);
this.openSnackbar("Category Not Added.");
}
return throwError("There is an issue with the call.);
}
//SNACK BAR METHOD
///////////////////////////////////////////////////////////////////////////
openSnackbar(snackMessage: string) {
this.zone.run(() => {
this._snackBar.open(snackMessage, "Close", {
duration: 7000
});
});
}
Unfortunately, this still yields the same results. Supposedly the fix above did work at one point, see here.
I have also tried doing the error handling in the component, which is not correct practice from what I understand, but I still got the same results even with the zone fix. Here is the error message I get in the console when the snackbar tries to fire:
core.js:1673 ERROR TypeError: this.openSnackbar is not a function
at CatchSubscriber.push../src/app/services/people-category.service.ts.PeopleCategoryService.handleError [as selector] (people-category.service.ts:93)
at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/OuterSubscriber.js.OuterSubscriber.notifyError (OuterSubscriber.js:13)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._error (InnerSubscriber.js:18)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:61)
Any insight would be appreciated! Thanks!