
Starting from the 5th version of Angular, the @angular/http module was deprecated for the new @angular/common/http module. Now we have a new object to call our backend, which basically introduces a generic type on the result to omit the classical .map(res:Response => res.json()).
The module import changes as follow:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule, HttpClientModule ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
A backend integration service can be rewrite as follows:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Event } from '../events/events.model';
@Injectable()
export class BackendService {
constructor(private httpClient: HttpClient) {}
getData() {
return this.httpClient.get< Event[] >('http://localhost:3000/api/');
}
}
The syntax is very concise and more expressive, great! But the most interesting feature is the possibility to introduce your code in the pipeline of the request: now you can do something previously and after the effective HTTP call with one or more interceptors. You can then create your pipeline of HTTP Request and the possibilities are endless. To make some examples:
- Add something to the header request previous the HTTP invocation, for example, the authentication token or whatever you want;
- Transform the response as you prefer after the HTTP invocation;
- Logging the HTTP activities;
- Centralize the HTTP error management;
- Redirect to login if receive a 401 error, or try again the operation.
The limit is your fantasy or, maybe, your requirements.
Thanks to Typescript is very simple to create an Interceptor:
- Create a class that implements the interface Interceptor;
- Implement the intercept method to do what you want;
- Register the class in the module providers section.
If you use Visual Studio Code and you have installed the John Papa snippets, you can use a snippet to create an interceptor:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req);
}
}
You can add all the interceptors that you need, they will be evaluated in the registration order:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MyFirstInterceptor } from './shared/myfirstinterceptor';
import { MySecondInterceptor } from './shared/mysecondinterceptor';
@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule, HttpClientModule ],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyFirstInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: MySecondInterceptor,
multi: true,
}],
bootstrap: [AppComponent]
})
export class AppModule { }
In the Raptor Framework, we use interceptor for more activities, one of this is the authorization error management: if I receive a 401 HTTP error code I will redirect the user to login:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router, ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/do';
@Injectable()
export class RaptorInterceptor implements HttpInterceptor {
constructor( private router: Router) { }
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req)
.do((event: HttpEvent) => {
if (event instanceof HttpResponse) {
// TODO: logging
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.router.navigate(['login']);
}
}
});
}
}
I will show you this case at my session about Raptor Framework, on November 29th at WPC 2017, don’t miss out!
See you soon