Angular application with HTTP Interceptor
Let us create an angular application and use http interceptor to intercept the requests.
Step 1: Create an angular application
We can make use of the angular cli to create a new application using
ng new http-interceptor
Folder Structure
Dependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
Step 2: Make an HTTP request
It will create a simple http get request using the angular’s HttpClient so that we can intercept it and to use that we will need to import provideHttpClient in our app.config.ts.
<!-- app.component.html -->
<div>
<input type="text" [(ngModel)]="name">
<button (click)="sampleRequest()">Make Request</button>
@if (response) {
<div>
<h2>Response</h2>
<pre>{{ response | json }}</pre>
</div>
}
</div>
/* app.component.scss */
div {
width: fit-content;
margin: 8px auto;
button {
display: block;
margin: 4px auto;
}
}
// app.component.ts
import { JsonPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, FormsModule, JsonPipe],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
})
export class AppComponent {
title = 'http-interceptor';
name = 'John';
response: any = null;
constructor(private httpClient: HttpClient) {
this.sampleRequest();
}
sampleRequest() {
this.httpClient
.get(`https://api.agify.io/?name=${this.name}`)
.subscribe((data) => {
this.response = data;
});
}
}
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient()],
};
Once you have made this changes you will be able to make a get request on button click.
Step 3: To start the application run the following command
ng serve
Output
Step 4: Creating Http Interceptor
We can create an interceptor to log how much time the request takes to complete. We will create a file http.interceptor.ts in the app directory and update its content as below.
// http.interceptor.ts
import {
HttpRequest,
HttpResponse,
HttpInterceptorFn,
HttpHandlerFn,
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
export const httpInterceptor: HttpInterceptorFn = (
req: HttpRequest<unknown>,
next: HttpHandlerFn
) => {
const started = Date.now();
return next(req).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
const elapsed = Date.now() - started;
console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
}
})
);
};
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { httpInterceptor } from './http.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withInterceptors([httpInterceptor])),
],
};
Output
HTTP Interceptors in Angular
In Angular, HTTP interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses at a centralized location. They act as middleware, sitting between the application’s HTTP client (typically the built-in HttpClient module) and the server.