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.

One of the most famous usages is to implement authentication. Interceptors are very useful when one wants to append a header in each request or want to manipulate the response before it reaches the actual calling party. It can also be used to show and hide loader on the screen based on http call.

Another use is to return json object as response as we use the .map method in every request’s response to return res.json, so the response can be hijacked or intercepted to do the same for all the requests.

Angular2  has not implemented the concept of interceptor but this can be done by extending the HTTP service. There are few steps that you need to follow to make this working.

1) Extend Http Service to provide your own functionality

// http-interceptor.ts
import { Injectable } from'@angular/core';
import { Http, XHRBackend, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import{ Observable } from'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class HttpInterceptor extends Http {
     constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
         super(backend, defaultOptions);
     }
     /**
     * Error handler to handle is there is any error 
     * @param error 
     * @param caught
     * @returns {ErrorObservable}
     */
     private onCatch(error: any, caught: Observable<any>): Observable<any> {
         if (error.status === 500) {
             return Observable.throw(newError(error.status));
         }
         else if (error.status === 401) {
             return Observable.throw(newError(error.status));
         }
     }
      
      // interceptor method to intercept request and response
     get(url: string, options?: RequestOptionsArgs): Observable<any> {
         // options and url can be updated here to append new headers
          options.headers = {'Authorization' : 'token'};
         return super.get(url, options)
                     .catch(this.onCatch)
                     .map((res: Response) => {
                         // on sucess return res.json
                         return res.json();
                      }, (error: any) => {
                           console.log("On error :(");
                      })
                     .finally(() => {
                         console.log('After the requset has been completed :)');
                     });
     }
}

2) Add this extended service in app.module.ts

providers: [{
    provide: HttpInterceptor,
    useFactory: httpInterceptor,
    deps: [XHRBackend, RequestOptions]
}]

Where httpInterceptor is an exported function that returns the new instance of extended HttpInterceptor class.

// to return an instance of HttpInterceptor class
export function httpInterceptor (backend: XHRBackend, defaultOptions: RequestOptions) {
    return new HttpInterceptor(backend, defaultOptions);
}

Instead of creating this function one can directly use the function in provider section but this creates problem while bundling the project. The following error can be encountered

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference
to an exported function (position 45:5 in the original .ts file), resolving symbol AppModule in D:/SK/Study/Material/MDCAngular/src/app/app.module.ts

Now to use this extended class inject the implementation of HttpInterceptor class like this where you want to inject http service

constructor (private http: HttpInterceptor) { }

Further Reading

Http Interceptor : Intercepting HTTP requests and response in Angular4

References

https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462


Leave a Reply

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

Related Posts

Angular

Http Interceptor : Intercepting HTTP requests and response in Angular4

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 Read more…