Angular Interceptor for all HTTP requests

October 7, 2022 · 2 min readLucian Ciobanu
Tags:AngularInterceptor

As part of a request to create audit data, the team realised we would need the username to be sent to the back end with every POST action so we agreed to have it sent in the headers of the request. There are numerous ways to do this but we thought interceptors would be the quickest.

user-interceptor.ts

import { Injectable } from "@angular/core";
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { LoginService } from "../services/login/login.service";

@Injectable()
export class UserInterceptor implements HttpInterceptor {
  private userName: string;
  
  constructor(private loginService: LoginService) {
    this.loginService.$login.subscribe(user => this.userName = user.UserName);
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.method === 'POST') {
        req = req.clone({
          setHeaders: { 'user': this.userName }
        });
        return next.handle(req);
      }

      return next.handle(req);
  }
}

In the app.module.ts we added the interceptor files

//...
import { HttpClientModule, HTTP_interceptors } from '@angular/common/http';
import { UserInterceptor } from './shared/utilities/user-interceptor;

//...
providers: [
  //...,
  {
    provide: HTTP_INTERCEPTORS, useClass: UserInterceptor, multi: true
  }
],
//...

And that's all, now all the post requests will have the user name set in the headers and the back end logic can use it for auditing.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery