Angular 4+ 中特定路由的 HTTP_INTERCEPTOR

3
我创建了HTTP_INTERCEPTOR,我需要它在某些特定的路由上工作,而在其他一些路由上不工作。
一开始它在主应用程序模块文件中, 然后我将其从那里移除,并添加到某些模块中,但它仍然在所有路由上工作,然后我将其添加到component.ts中,但根本不起作用。
{
            provide: HTTP_INTERCEPTORS,
            useClass: AuthExpiredInterceptor,
            multi: true,
            deps: [Injector]
},
1个回答

14

无法仅针对特定路由和/或模块指定拦截器。

但是,您可以添加一个HTTP头值,以跳过应用该请求的拦截器。例如:

import { HttpHeaders } from '@angular/common/http';
export const InterceptorSkip = 'X-Skip-Interceptor';
export const InterceptorSkipHeader = new HttpHeaders({
  'X-Skip-Interceptor': ''
});

在我的错误处理拦截器中,如果应用了头部信息,请不要捕获错误并处理它,而是让它冒泡到我的服务和组件中。

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>,next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (request.headers && request.headers.has(InterceptorSkip)) {
      const headers = request.headers.delete(InterceptorSkip);
      return next.handle(request.clone({ headers }));
    }
    return next.handle(request).pipe(catchError(this.processError));
  }


  ...

}

如果您希望忽略某个HTTP请求,请将InterceptorSkipHeader添加到该请求中。

this.http.get<ResponseModel>('api/url', { headers : InterceptorSkipHeader });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接