在 Angular Interceptors 中获取当前路线

问题描述 投票:0回答:2

我想知道是否有一种方法可以在 Angular 的 HttpInterceptor 中检索当前路由。我从不同的路线使用相同的拦截器,但我需要检查是否从特定的路线使用拦截器。如果是这样,我想在执行之前向后端的请求添加特定的标头。

似乎 RouteRouterActivatedRouteActivatedRouteSnapshot 对此不起作用。

我目前正在使用 windows.location 作为临时解决方案,但想知道在 HttpRequest 拦截器中执行此操作的正确方法是什么。

我当前的代码:

@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);
  }
}

工作示例:

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);
  }
}
angular angular-routing interceptor angular-router angular-http-interceptors
2个回答
5
投票

执行此操作的最佳方法是通过路由器对象来执行此操作:

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

很抱歉回答晚了,但我发现了同样的问题,并努力寻找最佳解决方案。所以我把它贴在这里供参考。


0
投票

在某些情况下,

router.routerState.snapshot
值将为空。我不认为使用浏览器窗口对象有什么问题。

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

© www.soinside.com 2019 - 2024. All rights reserved.