API在angular中使用拦截器时两次调用

时间:2018-08-20 19:40:46

标签: angular

我正在使用两个拦截器来拦截每个请求。如果API调用无法与后端通信,则一个用于添加令牌,另一个用于显示错误。

令牌拦截器

@Injectable()
export class TokenInterceptor implements HttpInterceptor{
  authService?: AuthService;
  constructor ( private inj: Injector,public errorHandler: ErrorHandler, ) {}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return this.authService
        .retrieveToken((req.url))
        .mergeMap((token: string) => {
          if (token !== null) {
            const request = req.clone({setHeaders: {Authorization: `Bearer ${ token }`}});
            return next.handle(request);
          }
          return next.handle(req);
        });
}

错误拦截器

@Injectable()
export class RequestInterceptor implements HttpInterceptor {

  constructor(
    public errorHandler: ErrorHandler,
  ) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).do((event: HttpEvent<any>) => {
          console.log(request);//It's displaying twice
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        this.errorHandler.handleError(err);
      }
    });
  }
}

service.module.ts

@NgModule({
  imports: [
    HttpClientModule
  ],
  exports: [
    HttpClientModule
  ],
  declarations: [],
  providers: [
    DataService,
    ErrorHandler,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true,
    },
    AuthService,
    AdalService,

  ]
})
export class ServicesModule { }

当我在Error Interceptor中对请求进行控制台时,我无法找出请求两次调用的原因。如何停止两次调用?

0 个答案:

没有答案