Advantages of Interceptors In an angular

Introduction

  • An interceptor in Angular is a piece of middleware that catches HTTP requests and replies. Globally, interceptors are used to alter or modify HTTP requests and replies. This implies that you may alter a single HTTP request or response and have an impact on all subsequent HTTP requests or answers that pass through that same location.

Ininterceptors In Angular

In Angular, interceptors are a potent tool that may be used for a broad range of activities, including

  • Adding authorization headers to requests
  • Logging requests and responses
  • Adding or removing parameters from requests
  • Transforming response data

How to implement an interceptor in Angular?

  • You must develop a class that implements the HttpInterceptor interface in order to implement an interceptor in Angular. Implementing intercept() and handleError, two methods of the HttpInterceptor interface, is optional ().

Let’s begin, then. Here is an illustration of an HTTP request interceptor that inserts an authorisation header:

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
        // Get the access token from your authentication service
        const accessToken = this.authService.getAccessToken();
        // Clone the request and add the authorization header
        const authRequest = request.clone({
            headers: request.headers.set('Authorization', `Bearer ${accessToken}`)
        });
        // Pass the cloned request to the next handler in the chain
        return next.handle(authRequest);
    }
}
  • In this instance, the intercept() function is overridden by the AuthInterceptor class, which also implements the HttpInterceptor interface. The intercept() function copies the incoming request and adds an authorization header after retrieving the access token from our authentication service. Using the next.handle() function, we then transmit the cloned request to the subsequent handler in the chain.

Register this interceptor with the Angular HTTP client in order to use it. You may achieve this by including it in your AppModule’s provider’s array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AuthInterceptor } from './auth.interceptor';

@NgModule({
    imports: [BrowserModule, HttpClientModule],
    providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
    }]
})
export class AppModule {}
  • In this example, we import the AuthInterceptor class and the HttpClientModule. The HTTP INTERCEPTORS token is then used to add our interceptor to the provider’s array. When the multi-option is set to true, this HTTP interceptor will be included in the list of already-existing HTTP interceptors rather than taking its place.

Benefits of using interceptors in Angular

  • Interceptors make it simple to add cross-cutting issues like authentication and error handling since they allow for the global modification of HTTP requests and answers.
  • Since they offer a single location to change requests and answers, interceptors help lessen code duplication.
  • You may simply alter the behavior of your application without having to edit each HTTP request and response by adding or removing interceptors.

conclusion

  • A potent Angular feature that enables global HTTP request and response manipulation is called an interceptor. They offer a centralised location to alter requests and answers and may be utilised for a variety of functions. You may simply add or delete functionality from your application and eliminate code duplication by making use of interceptors.

Submit a Comment

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

Subscribe

Select Categories