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

What is Interceptor?

Generally the interceptor an object or place where you can intercept the client request and server response globally. It is very useful when you want to ensure the header and ensure the property in the payload.

Why we need to add interceptor?

By adding the interceptor, we can easily intercept all the http client requests and responses. The most common case where we use the interceptor is, add the Authorization header or any other header in all HTTP requests and handle the error response.

Say for example, if you are getting the 403 error response from your back end service you should show some error and you have to redirect into the login page. In your application you may have multiple service call. Handling that error response in each and every service call is a little hard. And it will be increasing the lines of code. To avoid this case you can simply add the interceptor and handle the error response there.

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 { }

Conclusion

Happy to see you here. If you are here I believe you completely read my blog. Now you should have some idea about, what is interceptor, why we need to add and how we can add it.