Categories
Angular

Interceptor in angular

Interceptor in angular will intercept each http request and response also error

Syntax

interface HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}

CLI command to create interceptor

Once you created the angular application, naviagate to root folder and execute below command to create interceptor

ng g interceptor (name)

Now a class will be created as like below

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

@Injectable()
export class MyappintercepInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request);
  }
}

The class should implement HttpInterceptor interface. The method intercept will handle the request and response

You should add this interceptor in your app module.ts file in the provider section as like below

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AgGridModule } from 'ag-grid-angular';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyappintercepInterceptor } from './myappintercep.interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([]),
    AppRoutingModule
  ],
  providers: [{provide: HTTP_INTERCEPTORS, useClass: MyappintercepInterceptor, multi: true }  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

You have to clone the request to add token in the http request headers as like below

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

@Injectable()
export class MyappintercepInterceptor implements HttpInterceptor {

  constructor() {}

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

    request = request.clone({
      setHeaders: {
        'apptoken': 'SYSTEM'
      }
    });
    
    return next.handle(request);
  }
}

Leave a Reply

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