DEV Community

Parth Shukla
Parth Shukla

Posted on

Interceptors in Angular (Authentication, Caching, Logging, Error Handling)

Angular interceptors are merely a special kind of HTTP client service that has the sole purpose of intercepting every HTTP request performed. This is true for both incoming and outgoing HTTP requests. OK, I’ve seen this quick definition in several places, but what does that exactly mean? How does it work?

When the response arrives from the back end the Interceptors can transform it before passing it to our application.

One of the main benefits of the Http Interceptors is to add the Authorization Header to every request. We could do this manually, but that is a lot of work and error-prone. Another benefit is to catch the errors generated by the request and log them.

  1. Creating an HTTP Interceptor

We create an Injectable service that implements HttpInterceptor interface and thus must implement method Intercept


@Injectable() export class DemoHttpInterceptor implements HttpInterceptor {
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //do whatever you want with the HttpRequest
    return next.handle(req);
}

Enter fullscreen mode Exit fullscreen mode

Then add the class in Root Module

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

Enter fullscreen mode Exit fullscreen mode

Basic Auth Example using Http Interceptor

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { AuthState } from '../../store/auth.state';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private authService: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(this.addAuthToken(request));
  }

  addAuthToken(request: HttpRequest<any>) {
    const token = this.authService.getAuthToken();

    return request.clone({
        setHeaders: {
          Authorization: `Basic ${token}`
        }
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)