Implementing Interceptors in Angular: A Step-by-Step Guide with Examples

Nitinabansode
3 min readJun 14, 2023

--

Introduction:

Interceptors are a powerful feature in Angular that allow you to intercept and manipulate HTTP requests and responses. They provide a way to centralize common functionalities, such as adding headers, handling authentication, logging, and error handling, among others. In this blog post, we will explore how to implement interceptors in Angular, step by step, with real-world examples to help you understand their usage and benefits.

  1. Understanding Interceptors in Angular

In this section, we’ll provide an overview of interceptors and their purpose in an Angular application. We’ll explain how interceptors sit in the middle of HTTP requests and responses, allowing us to modify and inspect them before they reach the server or client.

2. Setting Up the Angular Project

To get started, let’s set up a new Angular project. Open your terminal and follow these steps:

$ ng new interceptor-demo
$ cd interceptor-demo

3. Creating an HTTP Interceptor:

Next, we’ll create an HTTP interceptor using the Angular CLI. Interceptors are classes that implement the HttpInterceptor interface. Run the following command to generate a new interceptor:

$ ng generate interceptor logging

This will create a new interceptor file named logging.interceptor.ts in the src/app directory.

4. Registering the Interceptor:

To make the interceptor work, we need to register it with the Angular HTTP module. Open the app.module.ts file and import the interceptor:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LoggingInterceptor } from './logging.interceptor';

Then, add the interceptor to the providers array:

providers: [
{ provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
]

5. Modifying Request and Response: Let’s modify the interceptor to add custom headers to the request and log the response. Open the logging.interceptor.ts file and update the intercept method:

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

export class LoggingInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modifiedRequest = request.clone({ setHeaders: { 'X-Request-ID': '123' } });
console.log('Request:', modifiedRequest);

return next.handle(modifiedRequest).pipe(tap(response => console.log('Response:', response)));
}
}

6. Error Handling with Interceptors: Interceptors can also handle errors in a centralized manner. Let’s create an error handling interceptor to log and handle HTTP errors. Generate a new interceptor:

$ ng generate interceptor error-handling

Update the intercept method in the error-handling.interceptor.ts file:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

export class ErrorHandlingInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
console.error('Error:', error);
// Handle the error or rethrow it
return throwError(error);
})
);
}
}

7. Adding Authentication to Interceptor: Interceptors are commonly used for adding authentication headers. Let’s create an authentication interceptor to add an authorization header to outgoing requests. Generate a new interceptor:

$ ng generate interceptor auth

Update the intercept method in the auth.interceptor.ts file:

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

export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modifiedRequest = request.clone({ setHeaders: { Authorization: 'Bearer your-token' } });
return next.handle(modifiedRequest);
}
}

8. Conclusion: In this final section, we’ll summarize the key points discussed throughout the blog post. We’ll emphasize the benefits of using interceptors in Angular applications and highlight scenarios where they can significantly simplify code and improve maintainability. By the end of this blog post, you’ll have a solid understanding of implementing interceptors in Angular and be ready to leverage their power in your own projects.

Conclusion: Interceptors in Angular provide a way to centralize and customize the behavior of HTTP requests and responses in your application. They offer flexibility, reusability, and maintainability, enabling you to add common functionalities such as authentication, error handling, and request/response modification with ease. By following the step-by-step guide and examples in this blog post, you now have the knowledge to implement interceptors in Angular and enhance the functionality and performance of your applications. Happy coding!

--

--