Angular Http Interceptor

Http Interceptors are used to intercept any outgoing request from the application. With the help of http interceptors we can modify the request and the incoming response while making the api call.

The interceptor will contain 2 parameters,req and next. The req is the HttpRequest parameter and the next is the HttpHandler parameter.

Let's see how to create an interceptor in an application in an angular application.

Create a new angular application using angular cli command.

ng new angular-tutorial

Create a service to make api call.

ng g s services/http

This will create a service named http.service.ts in services folder. Now open the file and modify the code as below.

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
  providedIn: "root"
})
export class HttpService {
  constructor(private httpClient: HttpClient) {}

  get(url: string) {
    return this.httpClient.get(url);
  }

  post(url: string, data: any) {
    return this.httpClient.post(url, data);
  }
}

In the above service, we inject the HttpClient to the constructor to make api call. In the service we have created two functions.The get() function is used to make get call using httpClient parameter. Similarly, post() function takes two parameter, url and data object and using httpClient parameter we make post call.

Let's create an interceptor by entering the following command.

ng g s services/interceptor

Now modify the code as below.

import { Injectable } from "@angular/core";
import {
  HttpInterceptor,
  HttpEvent,
  HttpResponse,
  HttpErrorResponse
} from "@angular/common/http";
import { Observable, of, throwError } from "rxjs";
import { map, tap, catchError } from "rxjs/operators";
@Injectable({
  providedIn: "root"
})
export class InterceptorService implements HttpInterceptor {
  constructor() {}
  intercept(
    req: import("@angular/common/http").HttpRequest<any>,
    next: import("@angular/common/http").HttpHandler
  ): Observable<HttpEvent<any>> {
    const request = req.clone({
      headers: req.headers.set(
        "Authorization",
        "Bearer asdfajsffjasfasfashlfhlash"
      )
    });
    return next.handle(request).pipe(
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          console.log("API call success");
        }
        return event;
      }),
      catchError(error => {
        if (error instanceof HttpErrorResponse) {
          console.log("Error has occured while calling the api");
          return throwError(error);
        }
      })
    );
  }
}

Here we have implemented the HttpInterceptor to the service. The interceptor will take arguments. The req is of type HttpRequest which contains the entire request details and next parameter is of type HttpHandler which is used to handle the request.

In the above code we have cloned the request and have set a new header parameter Authorization. We cannot directly modify the request directly, so we need to clone the request and modify the request.

Next, to handle the new request we use the next parameter to call the handle function and pass the request as parameter.

The main idea is to add an Authorization parameter to the header for each request. Chain the pipe function after calling the handle function.

The map operator will get any response and check whether the response is of type HttpResponse instance and logs a message to console. If their is any error, then catchError function will be called and the error log message will be logged to console.

Finally, we need to register the interceptor in the app.module.ts file with the following code.

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppRoutingModule } from "./app-routing.module";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { InterceptorService } from "./services/interceptor.service";
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: InterceptorService,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Open the app.component.ts file and modify the code as below to simulate an api call.

import { Component, OnInit } from "@angular/core";
import { HttpService } from "../services/http.service";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  reqUrl = "https://reqres.in/api/users?page=2";

  constructor(
    private httpService: HttpService
  ) {}

  ngOnInit() {
    this.httpService.get(this.reqUrl).subscribe(
      (value: any) => {
        console.log(value);
      },
      error => {
        console.log(error);
      }
    );
  }
}

In the above code, we have injected the HttpService to make api call. In the ngOnInit life cycle, we call the get() function of httpService with reqUrl as parameter and subscribe to the observable. Need to unsubscribe this observable in ngOnDestroy lifecycle.

Now press F12 and switch to the Console tab to check the logs printed in the Console.


Most Read