A Taste of The New Angular HTTP Client

Netanel Basal
Netanel Basal
Published in
2 min readJul 9, 2017

--

Angular version 4.3.0-rc.0 is now available. In this release, we can see a new exciting feature we all waited for — an improved version of the HTTP client API.

HttpClient is an evolution of the existing Angular HTTP API, which exists
alongside of it in a separate package, @angular/common/http. This structure
ensures that existing codebases can slowly migrate to the new API.

Installation

First of all, we need to update all of our packages to version 4.3.0-rc.0.

Next, we need to include the HttpClientModule in our AppModule.

Now we are ready. Let’s see three new things we’ve all been waiting for.

JSON as default

JSON is an assumed default and no longer needs to be explicitly parsed.

We do not need to write the following code anymore:

http.get(url).map(res => res.json()).subscribe(...)

Now we can just write:

http.get(url).subscribe(...)

Interceptors Support

Interceptors allow middleware logic to be inserted into the pipeline.

Request Interceptor

If we want to register new interceptor, we need to implement the HttpInterceptor interface. This interface has one method that we must implement — intercept .

The intercept method will give us the Request object and the HTTP handler and expect us to return an observable of type HttpEvent.

The Request/Response objects need to be immutable. Therefore, we need to clone the original request before we return it.

The next.handle(req) method is invoking the underlying XHR with the new request and returns a stream of response events.

Response Interceptor

An interceptor may choose to transform the response event stream as well, by applying additional Rx operators on the stream returned by next.handle().

The last thing we have to do is to register the interceptors with the HTTP_INTERCEPTORS multi provider.

Progress events

Progress events for both request upload and response download.

If we want to get notified about the download/upload progress we need to pass { reportProgress: true } to the HttpRequest object.

There are two new features that we will not talk about today:

  • Post-request verification & flush based testing framework.
  • Typed, synchronous response body access, including support for JSON body types.

This was an overview of the new HTTP client and its main features. You can find the full source code here.

Follow me on Medium or Twitter to read more about Angular, Vue and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.