Since Angular 4.3, the Angular framework offer a new HTTP client named HttpClient. This HTTP client put forward a new interceptor mechanism. But, it turns out that this mechanism is common to the entire application.
Assume that you have to consume two Rest API from 2 different providers. With the current mechanism, and using the HttpClient service, the stack of interceptors will be the same for the both Rest API. This may be problematic due to an incompatibility between interceptors and Rest API. An interceptor running on a Rest API 1 may not be able to run on a Rest API 2.
A solution might be to create two HttpClient instances but … It is a pitfall. If you can create two HttpClient instances like that :
You cannot specify two HTTP_INTERCEPTORS stacks. These two instances of HttpClient use HTTP_INTERCEPTORS. Well then, how can we have multiple instances of HttpClient with their own HTTP_INTERCEPTORS ?
If we look up the Angular code, we can see the problem :
HTTP_INTERCEPTOR is trapped inside the HttpInterceptingHandler method. It’s this handler which is used by HttpClient. So, we just have to rewrite this method and pass this handler to HttpClient :
Now, we can create our two instances of HttpClient like this :
That’s all 😉 !
Les derniers articles par William Koza (tout voir)
- Do an upload with Angular and ngx-upload - 6 mars 2019
- How can we have multiple instances of HttpClient with Angular ? - 18 septembre 2018
- Retrieve your ngfactory, .metadata.json and .ngsummary.json with Angular 5 - 8 avril 2018