Learn about Angular interceptors

In Angular, interceptors are a powerful tool that allows you to intercept HTTP requests and responses. Interceptors are a way of adding custom logic to the HTTP requests and responses in your application.

Interceptors can be used for a variety of tasks such as adding authorization headers, modifying the request or response data, logging, caching, and much more.

Creating the interceptor

Here is an example of how you can create an interceptor in Angular:

  1. Create a new file called `auth.interceptor.ts` in your `src/app` folder.
  2. Add the following code to the file:
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Add authorization header to the request
    const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
    });
    
    // Pass the modified request to the next interceptor or to the HttpClient if there are no more interceptors
    return next.handle(authReq);
  }
}

In this example, we are creating an `AuthInterceptor` that intercepts HTTP requests and adds an authorization header to the request using a JWT token stored in the local storage.

Registering the interceptor

Register the interceptor in your app module by adding it to the providers array:

typescript
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ]
})
export class AppModule { }

n this example, we are registering the `AuthInterceptor` as an interceptor for all HTTP requests by providing it as a value for the `HTTP_INTERCEPTORS` token.

Now every time an HTTP request is made in your application, the `AuthInterceptor` will intercept it and add an authorization header to the request. You can add additional interceptors to handle different tasks and apply them to specific requests or groups of requests as needed.

A full video on interceptors can be found below: