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);
}
}
(new URL(req.url)).pathname === '/logout'
for example. – Section