Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  }
}
like image 522
skolic Avatar asked Nov 15 '19 13:11

skolic


People also ask

What is ActivatedRoute?

The ActivatedRoute is the API that holds observable data that you can use to react to events with. You can subscribe to specific observable properties to get data from it asynchronously. The ActivatedRoute also contains ActivatedRouteSnapshot.

What is Http_interceptors in angular?

HTTP_INTERCEPTORSlinkA multi-provider token that represents the array of registered HttpInterceptor objects.

How do you use angular interceptors?

Create the InterceptorImport all the essential modules required by the application, such as the observable, injectable, HTTP requests, HTTP handler, HTTP events, etc. Now, create a class implementing the HTTP interceptor in angular interface. Later, you need to create one interceptor method with two arguments.

What is Route config in angular?

A configuration object that defines a single route. A set of routes are collected in a Routes array to define a Router configuration. The router attempts to match segments of a given URL against each route, using the configuration options defined in this object.


1 Answers

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.

like image 149
Iván García García Avatar answered Nov 02 '22 16:11

Iván García García