Interceptor use case in angular app

 In Angular, interceptors are a powerful mechanism to intercept HTTP requests and responses, allowing you to modify them before they reach the server or the application, or after they are returned from the server.

A use case for an Angular HTTP interceptor could be:

  • Adding Authorization Headers: Automatically attaching a token to each HTTP request to authenticate API calls.
  • Global Error Handling: Catching any errors returned by HTTP requests globally and handling them in a centralized way.
  • Request Logging: Logging or tracking HTTP requests for debugging purposes.

Example: Adding Authorization Header (Use Case)

Let’s walk through a real-world use case where we will use an HTTP interceptor to add an Authorization Header to all outgoing HTTP requests.

1. Creating an HTTP Interceptor

First, you need to create an HTTP interceptor. In Angular, an interceptor is a service that implements the HttpInterceptor interface.

Run the following command to generate the interceptor:

bash
ng generate service interceptors/auth

This will create an auth.interceptor.ts file.

2. Modify the auth.interceptor.ts

Here’s an example of how you can modify the interceptor to add an Authorization header to every HTTP request. We'll assume you have a method to get the token from a service (like an authentication service).

typescript
// src/app/interceptors/auth.interceptor.ts import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { AuthenticationService } from '../services/authentication.service'; // Assuming you have this service @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private authService: AuthenticationService) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Get the token from your service (this could be a bearer token, JWT token, etc.) const token = this.authService.getToken(); if (token) { // Clone the request and add the Authorization header with the token const clonedRequest = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); // Pass the cloned request to the next handler return next.handle(clonedRequest); } // If no token, just pass the request along as is return next.handle(req); } }

3. Provide the Interceptor in Your Module

Now, you need to register the interceptor in your Angular application. Open your app.module.ts and add the interceptor to the providers array.

typescript
// src/app/app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; // Import these import { AppComponent } from './app.component'; import { AuthInterceptor } from './interceptors/auth.interceptor'; // Import the interceptor @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule // Add HttpClientModule to the imports array ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, // Register the interceptor multi: true // Important: Allow multiple interceptors } ], bootstrap: [AppComponent] }) export class AppModule { }

4. Authentication Service (for Token)

Create an AuthenticationService that will handle retrieving the token. It can fetch the token from local storage, session storage, or a global state.

typescript
// src/app/services/authentication.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class AuthenticationService { constructor() { } // Example method to get the token (you can adapt this to your needs) getToken(): string | null { return localStorage.getItem('authToken'); // Assuming token is stored in localStorage } }

5. Usage: Making HTTP Requests

Now, when you make HTTP requests in your app, the AuthInterceptor will automatically add the Authorization header to every request. Here’s an example of how to use HttpClient to make a request.

typescript
// src/app/some-component/some.component.ts import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-some', templateUrl: './some.component.html', styleUrls: ['./some.component.css'] }) export class SomeComponent implements OnInit { constructor(private http: HttpClient) { } ngOnInit(): void { this.http.get('https://api.example.com/protected-endpoint') .subscribe(response => { console.log(response); }); } }

Key Points to Remember:

  1. HTTP_INTERCEPTORS: Angular interceptors are provided through the HTTP_INTERCEPTORS injection token in the providers array of AppModule.
  2. Request Cloning: Interceptors modify requests by cloning them with req.clone(). This is necessary because HTTP requests are immutable.
  3. Authorization Token: In this example, the token is assumed to be in localStorage, but it could also be fetched from a service or other secure locations (like cookies).

Additional Use Cases for Interceptors:

  • Global Error Handling: You can use interceptors to catch and handle any errors from HTTP requests globally, displaying user-friendly error messages or logging errors.
  • Request/Response Logging: You can log details about the request and response, which can be useful for debugging.
  • Adding Custom Headers: Beyond authentication, you can add any custom headers like Content-Type, Accept, or X-Custom-Header in the interceptor.

Conclusion:

Interceptors in Angular provide a powerful and flexible way to handle tasks like authentication, logging, error handling, and modifying requests/responses globally across your application. They allow you to centralize common logic for HTTP requests, making your application more maintainable and secure.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics