Angular

Using HttpInterceptor In Angular 9

Here, we will learn about using HTTP_INTERCEPTOR in an Angular application. HTTP_INTERCEPTOR can be used in many ways like logging cache, logging error and setting Authorize token to every request whichever passes throughout Angular application.

Road map for developing the Application:

  • Creating an Angular project
  • Setup HttpClient in angular project
  • Create an HTTP_INTERCEPTOR
  • Register the Interceptor with our Angular application
  • Reading data from API using the HTTP client
  • Testing the Application to see the final result

Creating an Angular project

You should have a new angular project in which we have to implement the interceptor or any existing angular application.

Setup HttpClient in angular project

We need to import the HttpClient in the app.module.ts file as its the basic angular project format to first import the external libraries before using it.

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

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Create an HTTP_INTERCEPTOR

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthHelpers implements HttpInterceptor {
    constructor() { }

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

        request = request.clone({
            setHeaders: {
                Authorization: `Basic authentication-key`
            }
        });

        return next.handle(request);
    }
}

You can set any additional information in the request which passes through our angular application. Here, we are setting the Authorize token in the request by cloning the request.

It will set the Authorization header for every request which passes in the application.

Register the Interceptor with our Angular application

We need to register the Interceptor in the app.module.ts file in the providers, so angular can recognize the Interceptor.

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

import { AppComponent } from './app.component';
import { AuthHelpers } from './_helper/auth-helpers.interceptor';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';

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

Reading data from API using the HTTP client

Open the app.component.ts file and write the code for reading data from API in it.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private _http: HttpClient) { }

  ngOnInit() {
    this.getDummyData();
  }

  getDummyData() {
    this._http.get('http://dummy.restapiexample.com/api/v1/employees').subscribe(res => {
      console.log(res);
    });
  }

}

This API call will first pass with our HTTP_INTERCEPTOR before making the actual API call and will add the Authorization token to it.

Testing the Application to see the final result

Code in Action:

Shaikh Irshad

Sr .NET Developer

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago