Angular 7/6 | Handle HTTP Request and Response using Interceptors in Angular 4.3 plus versions

Angular Interceptor is a powerful feature which can be used in many ways for securing and handling many HTTP related phenomena. HTTP interceptors were available in AngularJS but were missing in Angular 2, so there was a missing gap to manipulate HTTP calls globally at one place.

In Angular 4.3 version HttpInterceptors interface was added to enable new possibilities in a real-world application.

What we can do using Interceptors?

Interceptors can be used in a number of ways in an application.

– Set request headers in HTTP calls like Content-Type or send any custom headers.

– Authenticate HTTP calls by setting Security tokens

– Show Spin Loaders/ Progress Bars as HTTPS calls are in progress.

Handle Errors in HTTP calls at one place

– Show Response messages using Notifications/ Toasts

In a nutshell, we can say whatever is possible to do with HTTP calls, can be achieved by Inceptors.

In this post, we will only discuss How to send custom Headers and handle Response and Error in HTTP Calls using Interceptors.

How to implement Angular Interceptors?

Adding Interceptors in Angular 4.3+ versions is very easy and includes very few steps. Let’s discuss implementations step by step.

Create a new project using Angular CLI (current version is 7.3.8)

$ ng new ng-interceptors
? Would you like to add Angular routing? (y/N) y
? Which stylesheet format would you like to use? CSS

$ cd ng-interceptors

Create an Interceptor

We will create a new Interceptor class named httpSetHeaders to set request headers. This will implement HttpInterceptor.

// httpSetHeaders.interceptor.ts
import { Injectable } from '@angular/core';
import {
    HttpInterceptor,
    HttpRequest,
    HttpResponse,
    HttpHandler,
    HttpEvent,
    HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable()
export class httpSetHeaders implements HttpInterceptor {
    
    constructor(
        ) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


        if (!request.headers.has('Content-Type')) {
            request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
        }

        request = request.clone({ headers: request.headers.set('Accept', 'application/json') });

        request = request.clone({ headers: request.headers.set('Freaky', 'Jolly') });

        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    console.log('event', event);
                }
                return event;
            }),
            catchError((error: HttpErrorResponse) => {
                let data = {};
                data = {
                    domain: error.domain,
                    message: error.message,
                    reason: error.reason
                };
                console.log(data);
                return throwError(error);
            }));
    }
}

Above class implements HttpInterceptor which will call intercept method to take control of the HTTP call. Here we made changes to HTTP headers by using the clone method as we can’t make changes to read only responses and requests.

Add Interceptor in app.module.ts file

Next, we need to add created interceptor in the app’s module and also HTTP_INTERCEPTORS in providers.

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

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

import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http';
import { httpSetHeaders } from './httpSetHeaders.interceptor';

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

Now whenever a new HTTP request will be made, this Interceptor will modify the Headers of request. We can easily handle responses and errors by calling catchError method.

 

 

 

Leave a Comment

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