Angular 4.3 HTTPClient API

Rick HerrmannIn the 4.3 release of Angular, there was a new HttpClient API introduced.  HttpClient is an alternative to the existing Http module and exists in its own package (@angular/common/http).  For any projects that are using Angular 4.x, both Http and HttpClient are supported so you don’t have to migrate to the HttpClient all at once.  However, in Angular 5x, the original HttpModule is deprecated so only HttpClient is supported.  Hopefully with this overview you will see that HttpClient is actually easier to use and switching from Http will simplify your http service calls.

The HttpClient has an API that is streamlined with the the most common use cases in mind.  Prior to HttpClient, a common service call pattern looked like:

getProducts(): Observable {<br>
    return this.http.get('')<br>
        .map((response: Response) =&gt; response.json())<br>
        .map(json =&gt; json as Product[]);<br>

This a very routine API call to get an array of Products from a backend, including casting the json to a Typescript Product model.  Let’s contrast this with the same call using the new HttpClient:

getProducts() : Observable {<br>
    return this.httpClient.get('');<br>

This approach assumes we want json, and when you supply a type to the get call the cast is done automatically.  I find this much cleaner and easier to read.  What about the cases where you want to access more information – for example, the http response code?  The .get function takes an optional second parameter, so we can still access the response object with:

getProducts() : Observable {<br>
    return this.httpClient.get('', { observe: 'response' })<br>
    .map((response: HttpResponse) =&gt; {<br>
      // check response.status etc..<br>

This syntax applies to POST, PUT, DELETE, and PATCH as well.  So none of the functionality from the deprecated Http module is lost, but the most common use case has become a lot simpler to use.


Http Interceptors exist in AngularJs, but they were not a feature of Angular until the HttpClient was introduced.  If you are not familiar with what an interceptor does, it is basically a way to hook into every outgoing http request and  – most commonly – modify the request before sending it.  I think the most common use of interceptors has been to append an Authorization header that is saved locally.  To work around the lack of the interceptor feature in the original HttpModule, we would typically create a wrapper around the Http class – call it SecureHttp – and append the header before each get, post etc.  Now that interceptors are available in Angular there is no need to wrap the Http class.  A typical Interceptor implementation is shown below.  A few things to note:

  1. An Interceptor implements the HttpInterceptor interface, which has an intercept function
  2. This example assumes localStorage is used to store the API token from logging in – but there are other ways to do this
  3. If there is a local authToken, then a header is added to the request with the setHeaders function
  4. Notice that the incoming request is immutable and must be cloned to add the Authorization header (line 29)
  5. The successful API call is handled on line 34, and a failed call on line 37.  How you handle those is up to you but this example shows one possibility.
  6. So in addition to centralizing the task of adding the Authorization header to each request, we can also provide common Http error handling.http

To register the Interceptor with the application, you must add it the providers array in the app.module:

    provide: HTTP_INTERCEPTORS,<br>
    useClass: AuthInteceptor,<br>
    multi: true<br>

It is possible to have more than one HttpInterceptor in your application.  In addition to setting Authorization headers and handling errors, a second Interceptor could perhaps be used to log all Http calls or record other diagnostic information.

HttpInterceptors were a nice feature in AngularJS, and it is good to have them finally added to Angular.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s