In the previous post, we have seen how to intercept the http request and response by extending Http class from @angular/http module.
To recall an http interceptor is

Interceptors are components that intercept calls and are used for logging, auditing, security and to implement authentication.

An Http interceptor is a middleware that can hijack http request/call before it reaches to the server and its response before it reaches the actual targeted function.

In Angular2 there was no cleaner way to implement interceptors, But Angular4 has an elegant and cleaner way to do this.  

What are we going to do?

We will create an interceptor class that will intercept the response object to check if the response status is 401 that is Unauthorized then the user will be redirected to the login page.

How?

To Create interceptor we will create a class HttpServiceInterceptor that will implement the HttpInterceptor interface from @angular/common/http module and register the same as providers in app.modules.ts. Following are simple steps to achieve the same

1) Create a class (HttpServiceInterceptor) and implement HttpInterceptor interface

@Injectable()
export class HttpServiceInterceptor implements HttpInterceptor { }

2) Provide definition to intercept method of HttpInterceptor interface

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
}

And the full code

// http-service-interceptor.ts
import { Injectable, Inject } from "@angular/core";
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from "@angular/common/http";
import { DOCUMENT } from "@angular/common";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/do";
@Injectable()
export class HttpServiceInterceptor implements HttpInterceptor {
    constructor( @Inject(DOCUMENT) private document: any) { }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).do(
            (event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    return event;
                }
            },
            (err) => {
                if (err instanceof HttpErrorResponse) {
                    if (err.status === 401) {
                        this.document.location.href =
                        `${this.document.location.protocol}//${this.document.location.hostname}:${this.document.location.port}/login`;
                    }
                }
            });
    }
}

3) Import HttpClientModule and HTTP_INTERCEPTORS from @angular/http/common module

import { HttpClientModule,HTTP_INTERCEPTORS } from "@angular/common/http"; // to make http request
import { HttpServiceInterceptor } from "../interceptors/http-service-interceptor"; // response interceptor

4) Make an entry for HttpClientModule in imports array

imports: [
  HttpClientModule
]

5) Add provider for HTTP_INTERCEPTORS and use the class (HttpServiceInterceptor) that we created for interception

providers: [{
   provide: HTTP_INTERCEPTORS,
   useClass: HttpServiceInterceptor,
   multi: true
}],

6) Then use HttpClient instead of http as your http service

import { HttpClient } from "@angular/common/http";

7) Inject in the constructor

constructor(private http: HttpClient) { }

That’s all folks!! Isn’t it easy? Oh yes..

Leave Comment

Your email address will not be published. Required fields are marked *

en_USEnglish
en_USEnglish