如何使角度模块忽略核心模块中添加的http拦截器

问题描述 投票:32回答:2

我有一个带有HttpInterceptor的核心模块用于授权处理,我在AppModule中包含了这个模块,这样使用HttpClient的所有其他模块都使用这个拦截器。

@NgModule({
  imports: [],
  declarations: [],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true,
    },
  ]
})
export class CoreModule { }

如何使模块绕过默认拦截器?

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: components,
  providers: [CustomService],
  exports: components,
})
export class ModuleWithoutInterceptorModule { }
angular angular-http-interceptors
2个回答
68
投票

你可以使用HttpBackend。

例:

import { HttpClient, ..., HttpBackend } from '@angular/common/http';

@Injectable()
export class TestService {

  private httpClient: HttpClient;

  constructor( handler: HttpBackend) { 
     this.httpClient = new HttpClient(handler);
  }
....

通过这种方式,服务不会被AuthInterceptor拦截。


27
投票

根据GitHub上的this suggestion,我们实现了一个简单的标头来识别不应被拦截的请求。在拦截器中:

export const InterceptorSkipHeader = 'X-Skip-Interceptor';

@Injectable()
export class SkippableInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.headers.has(InterceptorSkipHeader)) {
      const headers = req.headers.delete(InterceptorSkipHeader);
      return next.handle(req.clone({ headers }));
    }

    ...  // intercept
  }

}

然后,只要您想跳过特定请求的拦截:

const headers = new HttpHeaders().set(InterceptorSkipHeader, '');

this.httpClient
    .get<ResponseType>(someUrl, { headers })
    ...

请注意,使用此方法时,服务(而非拦截器)在拦截器的逻辑应用时选择;这意味着服务必须“知道”应用程序中的拦截器。根据您的使用情况,最好让拦截器决定何时应用逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.