Search code examples
angularangular-routinginterceptorangular-routerangular-http-interceptors

Get current route in Angular Interceptors


I was wondering if there is a way to retrieve the current route in an HttpInterceptor in Angular. I am using the same interceptor from different routes, but I need to check if the interceptor is being used from a specific route. If so, I want to add a specific header to the request for the backend before it is performed.

Seems that Route, Router, ActivatedRoute and ActivatedRouteSnapshot do not work for this.

I am using windows.location at the moment as a temporarily solution, but was wondering what would be the right way doing this within an HttpRequest Interceptor.

My current code for this:

@Injectable()
export class APIClientInterceptor implements HttpInterceptor {
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // Check if the call is done from the embed route.
    if (currentLocation.includes('/embed/')) {

      // Get the hash ID.
      const sIndex = currentLocation.lastIndexOf('/') + 1;
      const sLength = currentLocation.length - sIndex;
      const embedHash = currentLocation.substr(sIndex, sLength);
      console.log(embedHash);

      // Add the header to tell the backend to use client credential flow for this call.
      request = request.clone({
        setHeaders: {
            ...
        }
      });
    }

    // In all other cases, just pass the original request.
    return next.handle(request);
  }
}

Working Example:

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

@Injectable()
export class TestInterceptor implements HttpInterceptor {
  constructor(private router: Router) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(this.router.routerState.snapshot);
    return next.handle(request);
  }
}

Solution

  • The best way to do this is to do it through the router object:

    constructor(private router: Router) {
        console.log(this.router.routerState.snapshot);
    } 
    

    Sorry for the late answer, but I found the same problem and struggle a little bit to find the best solution. So I post it here for reference.