Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular : How to extend HttpClient?

I did not find in the documentation how to extend HttpClient or how to specify differents 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.

like image 610
eroak Avatar asked Aug 27 '17 15:08

eroak


People also ask

What is difference between HTTP and HttpClient in Angular?

The HttpClient is used to perform HTTP requests and it imported form @angular/common/http. The HttpClient is more modern and easy to use the alternative of HTTP. HttpClient is an improved replacement for Http. They expect to deprecate Http in Angular 5 and remove it in a later version.

How does Angular handle HTTP errors?

The basic way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError and catchError. The HTTP request is made, and it returns the data with a response if anything wrong happens then it returns an error object with an error status code.

Why do we use HttpClient in Angular?

Why Do We Need HttpClient? The front-end of applications communicate with back-end services to get or send the data over HTTP protocol using either XMLHttpRequest interface or fetch API . This communication is done in Angular with the help of HttpClient .

How would you write code to modify the response from an HTTP GET?

catch( (error: Response) => { return Observable. throw(error); } );


1 Answers

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

like image 93
GreyBeardedGeek Avatar answered Oct 04 '22 03:10

GreyBeardedGeek