Wednesday, October 24, 2018

intercept all http request in angular with lazy loading modules

Working with angular as a front-end, we need to make many rest API for HTTP requests to the server. in single page application, we need too many ajax/HTTP request and response so Requests could pass some pieces of information and header parameters to get some data from it. This is a base functionality in the client-server architecture. However, there are some cases that could be useful to do some action for each ajax/HTTP request.

if you are developing single page application than for security reason, you must have to use authentication token.

if you want to redirect to 404, 500 etc page form commonplace then intercept is most useful.

We can also capture every response from the server to validate something or handle errors globally. This requirement could be met using interceptors. They give us a facility to handle ajax/HTTP request before sending and after request.

In angular 2, angular 4, angular 5, etc we can make http-interceptors to modify/add header information like as add Bearer token with all HTTP request, handle 404,500 requests etc.

To intercept you can use HttpInterceptor service.

here the following demo is developed in angular 4.

"/http-interceptors/interceptor.ts"
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class Interceptor implements HttpInterceptor {

  constructor( private cookieService: CookieService ) { }

  //Syntax - get( name: string ): string;
  getCookie(key: string){
    return this.cookieService.get(key);
  }

  //check Cookie
  //Syntax - check( name: string ): boolean;
  checkCookie(key: string){
    return this.cookieService.check(key);
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(`AddTokenInterceptor - ${req.url}`);
     if(this.checkCookie("myapp-token")){
      let jsonReq: HttpRequest<any> = req.clone({
        setHeaders:{
          Authorization : `Bearer ${this.getCookie("myapp-token")}`
        }
      });
      return next.handle(jsonReq);
    }else{
      return next.handle(req);
    }
  }
}

"/http-interceptors/index.ts"
/* Http Interceptors */
import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { Interceptor } from './interceptor';

/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: Interceptor, multi: true },
];

"app.module.ts"
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

import { CookieService } from 'ngx-cookie-service';

import { httpInterceptorProviders } from './http-interceptors/index';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
  BrowserModule,
  HttpClientModule
],
  providers: [
    CookieService,
    httpInterceptorProviders
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

in the above demo, some basic steps are given below to understand it easily.

step 1 : create "http-interceptors" folder/directory in app folder/directory

step 2: create "interceptor.ts" file in "http-interceptors" folder/directory and copy above demo code and past it in this file

step 3: create "index.ts" file in "http-interceptors" folder/directory and copy above demo code and past it in this file.

step 4: import "index" file of the created interceptor in "app.module.ts" file as given above demo

step 5: Add "httpInterceptorProviders" in providers in "app.module.ts" file as given above demo

here we have used 'ngx-cookie-service' and import it in app.module.ts and interceptor.ts file because we have store token in the cookie and get it from the cookie.

In this demo logic Bearer token only added if myapp-token is available/stored in cookie

You can also get token form local storage if you are soring token in local storage.

from the above demo, you can add, modify, delete any header or response data and you can control all HttpClientModule request of '@angular/common/http'.

From the above, we can say that if you are using authentication token like as jwt-web token in back-end side, the intercept is most important to add Bearer token with all http/https request.

I hope you can use it easy but if you have any confusion about it you can write your query in the comment box.

No comments:

Post a Comment