我想知道是否有一种方法可以在 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);
}
}
工作示例:
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);
}
}
执行此操作的最佳方法是通过路由器对象来执行此操作:
constructor(private router: Router) {
console.log(this.router.routerState.snapshot);
}
很抱歉回答晚了,但我发现了同样的问题,并努力寻找最佳解决方案。所以我把它贴在这里供参考。
在某些情况下,
router.routerState.snapshot
值将为空。我不认为使用浏览器窗口对象有什么问题。
${window.location.pathname}${window.location.search}${window.location.hash}