我正在尝试制作HTTP拦截器,每当我从服务器收到错误的状态响应时,都必须向用户显示该响应。我发现this tutorial得到了很好的解释,但是对于我来说似乎不起作用,而且我不知道自己在做错什么。
这是我的作品:
app-http-interceptor.service.ts
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from "@angular/core"
import { Observable, of } from "rxjs";
import { tap, catchError } from "rxjs/operators";
import { ToastrService } from 'ngx-toastr';
@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(evt => {
if (evt instanceof HttpResponse) {
if(evt.body && evt.body.success)
this.toasterService.success(evt.body.success.message, evt.body.success.title, { positionClass: 'toast-bottom-center' });
}
}),
catchError((err: any) => {
if(err instanceof HttpErrorResponse) {
try {
this.toasterService.error(err.error.message, err.error.title, { positionClass: 'toast-bottom-center' });
} catch(e) {
this.toasterService.error('An error occurred', '', { positionClass: 'toast-bottom-center' });
}
//log error
}
return of(err);
}));
}
}
而且我在我的app.module.ts中:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptor,
multi: true
}
]
带有这些进口物:
import {AppHttpInterceptor} from './app-http-interceptor';
import {HTTP_INTERCEPTORS, ...} from '@angular/common/http';
当我在我的应用中强加500错误时,这是控制台输出:
fail callback TypeError: Cannot read property 'error' of undefined
请问我在做什么错?可以很好地捕获错误,并通过窗口警报对其进行测试。
您指的是err.error.message
,但我认为在查看HttpErrorResponse interface时不正确。尝试删除第二个error
属性。