Angular : How to extend HttpClient?

3.5k views Asked by At

I did not find in the documentation how to extend HttpClient or how to specify different interceptors for some of my HTTP requests. In documentation, they explain how to set interceptors in HTTP_INTERCEPTORS but every HTTP requests are intercepted.

I need to have customizes HttpClient implementations to set specifics Headers, endpoints or response interceptors (I don't want to use Restangular, I would prefer to use the built-in angular HttpClient implementation).

  • I have an oAuth API with a specific endpoint and specific header to set my api-key.
  • I also have my "resources" API that needs specific header (Authorization: Bearer ... and API-KEY) and a specific response interceptor to catch all HTTP 401 responses.
  • Maybe, i will need to call some externals API without any interceptors

I know this is possible with Restangular but I prefer to use HttpClient. How is it possible ?

I found this article but, this is for Http not for the new HttpClient implementation of angular.

1

There are 1 answers

5
GreyBeardedGeek On

Instead of extending HttpClient, I would take one of three approaches:

  1. Have each of your Interceptors inspect the URL of the request, and either do it's work, or just call next.handle(req) without doing anything else, depending on the URL

or

  1. Write a delegating Interceptor, that decides which other Interceptors to delegate to, depending on your requirements.

or

  1. Just write one big Interceptor that decides what do based on the URL / whatever you need.

My gut would be to go with #1