The New HTTP Client in Angular 4.3

0
2034

In Angular 4.3, a new HTTP Client was introduced. This new client replaces the @angular/http module you are using right now. To prevent breaking changes (👍), it was released under a different name so that people can slowly migrate to the new client. In this article, I want to show you what’s new and how to migrate!

What’s new

JSON is now the default response.
This is an huge positive change IMO, as there is really only like .1% you want anything else (sorry xml guys).

Interceptors are back!
In AngularJS, we had this same concept of middleware for our HTTP requests and the team brought it back in this new client. I recently authored an article that talked about how to do Authentication using JWT in Angular, in that article we had to override the BaseRequestOptions object in order to inject our JWT token. That had a side effect if the local storage changed, the request options would still pass the first one since that is a static class. Now that we have interceptors again, we can use those to inject our token like so:

Another handy thing you can do with interceptors is HTTP error handling. We can already do this by override the Global Error Handler class but this allows us to explicitly handle HTTP errors.

Upgrading

This is a breaking change so we are gonna have to change quite a few things.

First, lets replace the HttpModule in our app.module to use the new http client.

Before

After

You will notice we completely replaced the old http module with the new @angular/common/http http client.

Next, we need to update our services to use the new client.

Before

After

In the after example, we updated the following items:

  • Instead of injecting Http client, you now inject the HttpClient from our new module.
  • You no longer have to do .json() on your responses to get the data since that’s the default now.
  • In my get invocation, I actually use my model interface to describe the response.

If you were using things like Request options before, those have changed a little too. So an example of the old search params might look something like:

Now we just call them params. So the conversion would look like:

Wrapping Up

There are a few more changes but this should help you get a basic understanding of the changes. Angular updated the docs for the HTTP sectionto use the new HTTP client so check that out for more information. Overall, I think these are great changes and a step in the right direction!

Suggest

Angular 4 (formerly Angular 2) – The Complete Guide

Testing Angular 4 (previously Angular 2) Apps with Jasmine

Angular 4 (2+) Master Class for Beginners

Angular 4 Front To Back 

LEAVE A REPLY

Please enter your comment!
Please enter your name here