Get current route in Angular Interceptors
Asked Answered
A

2

10

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);
  }
}
Andrea answered 15/11, 2019 at 13:34 Comment(2)
Have you checked the answer?Shirty
If you landed here but were concerned with the backend URL, you can do it pretty cheaply with the URL API: (new URL(req.url)).pathname === '/logout' for example.Section
Y
7

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.

Yggdrasil answered 13/5, 2020 at 11:12 Comment(4)
I will need to verify this as I was not able to use the Router as expected in my case for the Interceptor, but maybe that has been changed in the meanwhile :) Will test this out and post an answer here asap. Thx for your reply Ivan.Andrea
I can confirm that it works now with the new Angular versions.Andrea
Doesn't work for me at all. snapshot.url parameter is an empty stringNiece
Extremely helpful! The only thing that worked for me between several SO posts. My use case is getting the current route url inside an httpInterceptor called from an canActivate Guard.Mccrary
I
0

Under some circumstances, the router.routerState.snapshot value will be empty. I don't think there's anything wrong with using the browser window object.

${window.location.pathname}${window.location.search}${window.location.hash}

Imitation answered 7/12, 2023 at 2:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.