Angular HttpClient
Why Do We Need HttpClient?
The front-end of applications communicates 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.
What Is HttpClient?
HttpClient is a built-in service class available in the @angular/common/http package. It has multiple signatures and returns types for each request. It uses the RxJS observable-based APIs, which means it returns the observable and what we need to subscribe to it. This API was developed based on XMLHttpRequest the interface exposed by browsers.
Here are some key things to bear in mind regarding this particular type of Observables returned by the HTTP module:
- if we don’t subscribe to these observables, nothing will happen
- if we subscribe multiple times to these observables, multiple HTTP requests will be triggered
- This particular type of Observable are single-value stream: If the HTTP request is successful, these observables will emit only one value and then complete
- these observables will emit an error if the HTTP request fails.
Features of HttpClient
- Provides typed request and response objects
- Intercepts request and response
- Supports RxJS observable-based APIs
- Supports streamlined error handling
- Performs the GET, POST, PUT, and DELETE operations
Making HttpClient Available In The Project
To be able to use the HttpClient service within your components we first need to include the HttpClientModule in the Angular application. First, we need to import the HttpClient module in the application’s root module in the file app.module.ts:
Once imported you can make use of HttpClient in your components. To make HttpClient available in the component class you need to inject it into the class constructor as you can see in the following:
HTTP GET Request
HttpClient.get() method is an asynchronous method that performs an HTTP get request in Angular applications and returns an Observable. And that Observable emits the requested data when the response is received from the server.
Let’s implement a simple example that uses GitHub’s REST API to request user data. Insert the following code in the file app.component.ts:
The output which is displayed in the browser console should look like the following:
The results show that it’s possible to directly access the JSON response by subscribing to the Observable which is returned from the get method.
Typed Response
From the console output, you can see that the returned JSON object has a lot of properties. If you now try to access one of those properties by using the dot notation you’ll get back an error:
console.log(data.login);
The error message is saying: “Property 'login' does not exist on type 'Object'”. As data is of type Object you can not access properties directly. However, we're able to cast the response Object to a type which is containing the corresponding properties. Let's define an interface type which is containing some of the properties which are part of the response:
Next, let’s make use of UserResponse to cast the return type of the get call:
Accessing the values by using data.login, data.bio and data.company is possible now. The output in the browser console should now deliver the following result:
HTTP Request Parameters
The HTTP GET can also receive parameters, that correspond to the parameters in the HTTP URL. Let’s take for example the following URL with id parameters:
This above query returns the same result as before. This is how we would do this query using the Angular HTTP Client:
Notice that we are building the HTTPParams object by chaining successive set() methods. This is because HTTPParams is immutable, and its API methods do not cause object mutation.
HTTP Headers
Almost every HTTP request including headers. Sometimes, REST API servers required additional header parameters on every request. For example, the secured REST API endpoint is only accessible with an Authorization header token, the specific REST API request uses a different type of response by determining the type from the HTTP headers.
Get Kevin Mavani’s stories in your inbox
Join Medium for free to get updates from this writer.
If we want to add custom HTTP Headers to our HTTP request, in addition to the headers the browser already attaches automatically we can do so using the HttpHeaders class:
HttpHeaders are also immutable i.e every method on HttpHeaders object does not modify it but returns a new HttpHeaders object.
HTTP headers are immutable
The HTTP headers are immutable. The following example does not work as each set method returns a new header and does not update the original header.
To workaround, you can use the code as follows
HTTP POST Request
Next, let’s see how data can be sent via HttpClient. For sending data we’ll be using the post method of the HttpClient object. Of course, we need a backend that offers a REST API that accepts POST HTTP requests. To avoid setting up our own backend API we can instead make use of JSONPlaceholder which is a fake online REST API for testing and prototyping (https://jsonplaceholder.typicode.com/).
The endpoint http://jsonplaceholder.typicode.com/posts is support POST HTTP requests. Let’s use that endpoint to create a new post record:
Here you can see that the data of the post request are passed to the post method as the second parameter in JSON format. We’re getting back a response which is confirming that the object has been created successfully:
HTTP Interceptors
One of the new features of the new HttpClient module is the availability of interceptors. Interceptors are sitting in between your application and the backend. By using interceptors you can transform a request coming from the application before it is actually submitted to the backend. The same is possible for responses. If a response arrives from the backend the interceptor can transform that response before it arrives in your application.
The best way to discover how interceptors work is to implement a simple example. Create a new file auth-headers.interceptor.ts and insert the following code:
The interceptor class AuthHeadersInterceptor implements the interface HttpInterceptor which is part of the @angular/common/http library. Implementing this interface requires us to add the intercept method to the class. This method is doing the main work of the interceptor. The method is expected to get two parameters. The first parameter is containing the original request. The second parameter is the next HTTP handler to which the request needs to be passed on for further processing.
In this first example, the intercepts method is just passing on the original request to the next handler. Having understood the interceptor approach we can now move on and manipulate the request in the intercept method:
First, we’re creating a new request by using the clone method. At the same time, we’re passing in a JSON object containing the headers property. We’re using the req.headers.set method to create a new header entry for the Authorization property. This property is used to submit the access token.
Finally, the newly created request object (with the header included) is passed on for further processing by using the next.handle method.
Providing The Interceptor
In order to activate the interceptor for our application we need to provide it to the main application module AppModule in file app.module.ts:
we’re inserting a new object to the array which is assigned to the providers property of @NgModule. This object is containing three properties:
- provide: needs to be set to HTTP_INTERCEPTORS in order to specify that an HTTP interceptor is provided
- useClass: needs to be set to our interceptor class type
- multi: needs to be set to multi to tell Angular that HTTP_INTERCEPTORS is an array of values, rather than a single value
Now the Interceptor is active and the Authorization header is added to every request which is sent out automatically.
Conclusion
HttpClientis a Service that comes with the Angular framework and enables you to make your app communicate with an A.P.I.- HTTP interceptors are a very powerful tool that helps us to customize HTTP requests and make any logic before the requests send out/get into our angular application.









