HTTP Interceptor in Angular

http interceptor

This article on HTTP Interceptor in Angular is part of the Learning Angular series.

Typically when we want to do soemthing with every request, it can be passe on to be done by an interceptor. In the current application case, the firebase auth token in the params.
auth.interceptor.ts

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

export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
    console.log('Intercepted ', req);
    return next.handle(req);
  }
}

HttpHandler gives a special method to let the request continue its journer\y, and if not done, the request won’t proceed.
Now to make it work, we need to tell Angular to use this interceptor
core.module.ts

providers: [
  ...
  { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } // multi tells Angular that we are going to use multiple interceptors.
  { provide: HTTP_INTERCEPTORS, useClass: AnotherInterceptor, multi: true }
]

Modifying Request in Interceptors

The HttpRequest is an inmutable bject. So we should not be changing the request directly.
What we can do is create a clone of that request by using

const clonedReq = req.clone()

But the principle of inmutability stands on the cloned request too. So one can’t direcvtly modify the attributes of the cloned request.
But the clone function gives the power to modify attributes of the request.

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) { }

  intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
    const reqClone = req.clone({
      params: req.params
                .set('auth', this.authServiuce.getToken())
                .append(...)
    });
    return next.handle(reqClone);
  }
}

Modifying Response in Interceptors

The same process can be followed for the response, but we need to atatcht he do operator to the request to check for the responses.

export class LoggingInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) { }

  intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
    return next.handle(req).pipe(
      tap(event => console.log('Loggin ', req)
    );
  }
}

Now this inteceptor needs to be provided in the Core Service
When there are multiple interceptors, they are run in the manner they havbe been privided in the providers array.

Leave a Reply