How to add HttpClient Interceptors conditionally in Angular

前端 未结 2 640
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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('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.

提交回复
热议问题