node.js - 响应拦截器的CatchError函数多次执行 - Angular 6
问题描述
我为我的 Angular 项目创建了一个拦截器来拦截所有请求和响应,但是验证响应中的错误的函数执行了 7 次。
我意识到,当我使用throwError
它rjxs
多次执行该功能时,如果我使用of
rxjs
它只执行一个,但无法执行验证订阅错误的功能。
constructor(private injector: Injector, public errorHandler: ApplicationErrorHandler) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const sessaoService = this.injector.get(SessaoService);
if (sessaoService.isLoogedIn()) {
const token = localStorage.getItem('token');
const tokenSplit = token.split(' ');
request = request.clone(
{ setHeaders: { 'Authorization': `${tokenSplit[1]}` } }
);
}
return next.handle(request).pipe(
catchError((err: HttpErrorResponse) => {
console.log('Execute function');
let data = {};
data = {
error: err,
status: err.status,
method: request.method
};
this.errorHandler.handleError(data);
return throwError(err);
})
);
}
我希望 catchError 函数只执行一次,但每个请求运行 7 次。
我的 Angular 版本是:6.1.3;我的 Rxjs 版本是:6.4.0;
对不起,我的英语不好...
解决方案
我发现了问题,我的应用程序中有一个共享模块,在其中我添加了 HTTP_INTERCEPTORS 作为提供程序,使用我的类和拦截函数。