Interceptor in Angular

What is an interceptor in angular?

Interceptors are a unique type of Angular Service that we can implement. Interceptors allow us to intercept incoming or
outgoing HTTP requests using the HttpClient. By intercepting the HTTP request, we can modify or change the value of the
request.
Interceptors are basic building blocks for Angular service so that we can implement them. Interceptors are allowed us to intercepts our incoming or outgoing HTTP requests using the Clients.
we can easily modify and change the value of its requests.

There are we have 3 different Interceptors Implementations:

Handling HTTP Headers
HTTP Response Formatting
HTTP Error Handling

What is the reason we have to use interceptors in our applications?

with the help of interceptors, we can easily use the features like caching & logging. Interceptors always work with each and every request and response.

We have always 2 arguments, req&next& returns observable of type Httpevent.

req- is itself request object type & of the type HTTP request.

next-is the HTTP Handler, of type HTTP Handler.

How do we modify requests with help of Interceptor?

As we know HTTP req.objects are immutable, so as we modify them, firstly we make a copy of that, then modify with that copy & call handler
on the modified copy of that interceptor.

Basic API implementation-

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(httpRequest);
}
}

If we want to create an interceptor, we have a need for the HttpInterceptor interface from the @angular/common/http package. Each and every time our application gave an HTTP request using the HttpClient service, the Interceptor which calls the intercept() method.

When this method is called Angular passes a reference to the httpRequest object. With this help and request, we can inspect this and modify the interceptor as necessary. Once we complete our logic, we call next. Handle method and return the new request onto the application part.

once our Interceptor is created, we have to register it as a multi-provider since there can be multiple interceptors running within an application. You must register the provider to the app.module for it to apply to all application HTTP requests.
Interceptors will only intercept requests that are made using the HttpClient service.

import { NgModule } from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import { HttpClientModule, HTTP_INTERCEPTORS } from ‘@angular/common/http’;
import { RouterModule, Routes } from ‘@angular/router’;

import { MyInterceptor } from ‘./my.interceptor’;
import { AppComponent } from ‘./app.component’;

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

HTTP Header Interceptor
A request Feature is frequently used to return an API key to a validated API end – point. We can standardise our entire application by using interceptors to manage this immediately. Let’s create a simple use case in which an API header key is attached to each request.

import { Injectable } from ‘@angular/core’;
import { HttpInterceptor, HttpEvent, HttpResponse, HttpRequest, HttpHandler } from ‘@angular/common/http’;
import { Observable } from ‘rxjs’;
import { map, filter } from ‘rxjs/operators’;

@Injectable()
export class HeaderInterceptor implements HttpInterceptor {

intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const API_KEY = ‘123456’;
return next.handle(httpRequest.clone({ setHeaders: { API_KEY } }));
}
}
We can use the replica process on the httpRequest object to adjust the request object and restore a replica. In this example, we attach the API KEY valuation as a header to every HTTP request using httpRequest.clone({ setHeaders: { API_KEY } }).

Now let’s use the HttpClient service to make a HTTP get request.

import { Component, OnInit } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;
import { Observable } from ‘rxjs’;
import { tap } from ‘rxjs/operators’;

@Component({
selector: ‘app-header’,
template: `
<h2>Header Example</h2>
<pre>{{ data | json }}</pre>
`
})
export class HeaderComponent implements OnInit {
output: {};
constructor(private httpClient: HttpClient) { }

ngOnInit() {
this.httpClient.get(‘/assets/header.json’).subscribe(data => this.output = output);
}
}

Leave a Reply