我对我的API请求有服务级别的错误处理。这非常有用,除了我希望能够通知用户,除了控制台消息以外,UI出现了问题。我认为Material Snackbars对此非常有用。
做完一些研究后,Angular HttpClient似乎在区域外运行,因此我将我的快餐条.open()方法包裹起来,以解决此问题:
//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
});
});
}
不幸的是,这仍然产生相同的结果。假设上面的修复程序确实在某一时刻起作用,请参见here。
我也尝试过在组件中进行错误处理,根据我的理解,这不是正确的做法,但是即使使用区域修复,我仍然可以获得相同的结果。这是当小吃栏尝试点火时我在控制台中收到的错误消息:
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)
任何见识将不胜感激!谢谢!