How to use Interceptor for Angular Error handling and Authentication using Http Client and Http Interceptor

How to use Interceptor for Angular Error handling and Authentication using Http Client and Http Interceptor

How Interceptor works?
It transform the outgoing service request before final send so that you can alter service request (API), also you
can catch errors globally in one place.



Please find below steps to implement Interceptor in Angular 4, Angular 5, Angular 6 and Angular 7
Step 1:

app.module.ts
Add below import for interceptor
import { ResponseInterceptor } from './services/app.response.interceptor';
Make entry in Providers
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    xyz
  ],
  providers: [
    { provide: 
    HTTP_INTERCEPTORS, useClass: 
    ResponseInterceptor, multi: 
    true },
    AuthGuardService],
  bootstrap: [AppComponent]
})

Step 2:
If your Angular version is 4 or 5 then as a prerequisite to implement Interceptor is you have to replace http request with http client like

import { Http } from '@angular/http'; 

Replace with below import

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

Step 3:
Create new file in service folder by name of app.response.interceptor.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/do';
import { environment } from 'path to environment/environments/environment';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
    //Get Auth Token from Service which we want to pass thr service call
    const authToken: any = `Bearer ${sessionStorage.getItem('jwtToken')}`
    // Clone the service request and alter original headers with auth token.
    const authReq = req.clone({
      headers: req.headers.set('Content-Type', 'application/json').set('Authorization', authToken)
    });
 
    const authReq = req.clone({ setHeaders: { 'Authorization': authToken, 'Content-Type': 'application/json'} });

    // Send cloned request with header to the next handler.
    return next.handle(authReq).do((event: HttpEvent) => {
      if (event instanceof HttpResponse) {
        console.log("Service Response thr Interceptor");
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        console.log("err.status", err);
        if (err.status === 401 || err.status === 403) {
          location.href = '/login';
          console.log("Unauthorized Request - In case of Auth Token Expired");
        }
      }
    });
  }
}

Now your all service request will go thr above file and you can manage service request, header and response thr this file.

Leave a Reply