10

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your comment. I think this approach doesn't respect separation of concerns (except for the first one ?!). But if I use the interceptors to set the api endpoints, I will not be able to inspect URL ?!
I wasn't suggesting setting the endpoints in the Interceptors, just setting whatever headers are required for the particular endpoint. I would think that your services should be responsible for knowing the endpoint url.
Each of my custom HttpClient implementation has its own constant URL endpoint and I don't want to use a getURLEndpoint()-like method.
just like @GreyBeardedGeek said It's not a good practice to set hard-coded URI endpoints into your providers. But if you don't want to change, you could use approach #1 or #2 easily.
I wasn't suggesting setting (hard-coding) the endpoints in the providers...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.