How to add HttpClient Interceptors conditionally in Angular

前端 未结 2 631
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 09:22

Recently I have been using Interceptors with Angular HttpClient.

I add headers corresponding to some HTTP GET methods and for some I do not need those headers.

相关标签:
2条回答
  • 2021-01-04 10:14

    I know it is too late however, we still do not have any solution from Angular. An easy workaround at the moment is to create a BehaviorSubject and activate the Interceptor according to the value it. With this, you are able to handle specifics HTTP requests the must use your Interceptors:

    yourService.service.ts

    public interceptorTwo = new BehaviorSubject<boolean>(null);
    
    someHttpmethod() {
       this.interceptorTwo.next(true);
    
       // Add your CODE http
       this.myHttp.post<any>('someUrl', data).finally(() => this.interceptorTwo.next(null));
    }
    

    yourInterceptorTwo.service.ts

    const setAuth = this.yourService.interceptorTwo.value;
    if (!setAuth) {
      return next.handle(req);
    }
    
    0 讨论(0)
  • 2021-01-04 10:16

    Note: I haven't tried this approach myself yet but have played with the idea because we are looking at a similar problem.

    If we had very simple requirements, it would be trivial to add logic in a general purpose interceptor and just decide based on URL/Method which kind of interception to perform. However, our angular app needs to call a variety of 1st party micro-services and 3rd party APIs with different requirements for interceptors. This is effectively a superset of your requirements.

    One idea to implement this is to extend HttpClient for each API/Service that we need to call and set up a custom injection token for the interceptor chain. You can see how angular registers the default HttpClient here:

     providers: [
        HttpClient,
        // HttpHandler is the backend + interceptors and is constructed
        // using the interceptingHandler factory function.
        {
          provide: HttpHandler,
          useFactory: interceptingHandler,
          deps: [HttpBackend, [new Optional(), new Inject(HTTP_INTERCEPTORS)]],
        },
    

    The interceptingHandler function is even exported as ɵinterceptingHandler. I agree this looks a little weird, not sure why it has that export name.

    Anyawy, to use a custom HttpClients you can probably:

    export const MY_HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('MY_HTTP_INTERCEPTORS');
    
    ...
     providers: [
        MyHttpClient,
        {
          provide: MyHttpHandler,
          useFactory: interceptingHandler,
          deps: [HttpBackend, [new Optional(), new Inject(MY_HTTP_INTERCEPTORS)]],
        },
    

    And make sure that MyHttpClient requires a MyHttpHandler in its constructor.

    0 讨论(0)
提交回复
热议问题