获取Angular Interceptors中的当前路线

时间:2019-11-15 13:34:03

标签: angular angular-routing interceptor angular-router angular-http-interceptors

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

似乎 Route Router ActivatedRoute ActivatedRouteSnapshot 对此无效。

目前,我正在使用 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);
  }
}

2 个答案:

答案 0 :(得分:1)

做到这一点的最佳方法是通过路由器对象来实现:

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

很抱歉无法提供最新的答案,但是我发现了同样的问题,并且为找到最佳解决方案付出了一些努力。所以我把它张贴在这里供参考。

答案 1 :(得分:0)

request.url 将给出当前路线。

尝试这样:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  let currentLocation = request.url;
  console.log(currentLocation );
   if (currentLocation.includes('/embed/')) {
     ...
   }
}
相关问题