Blog Detail

  • Home
  • How to add Interceptor in Angular

How to add Interceptor in Angular

In this post you can see, how to add interceptor in Angular 2 and above and why we need to add that. first you have to create the Interceptor.ts file. that should be there in app folder. And import it in app.module.ts

Why we need to add interceptor?

By adding the interceptor we can easily intercept all the http client request and response. If any need to add Authorization header or and specific header you can simple add here instead of change the all service files.

Interceptor.ts

import { Inject, Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse,
  HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError, tap } from 'rxjs/operators';
import { ActivatedRoute, Router } from '@angular/router';
@Injectable()
export class Interceptor implements HttpInterceptor {
  constructor(private router:Router, private actRouter:ActivatedRoute) {}

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

      request.headers.set('Access-Control-Allow-Origin','*');

      return next.handle(request).pipe(
      //retry(1),
      tap(event => {
        // There may be other events besides the response.
        if (event instanceof HttpResponse) {
          
        }
      }),
      catchError((error: HttpErrorResponse) => {
        //console.error(error.status, error.statusText, error);        
        let errorMessage = '';
        if(error.statusText == 'Unknown Error'){
         // location.replace(Service.SERVER+'/login')
        }
        return throwError(error);
      })
    );
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http';=

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { Interceptor } from './config/Interceptor';

@NgModule({
  declarations: [
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule, 
  ],
  providers: [{provide: HTTP_INTERCEPTORS, useClass: Interceptor,multi: true}],
  bootstrap: [AppComponent]
})
export class AppModule { }

Write a comment