sko*_*lic 6 interceptor angular-routing angular-http-interceptors angular angular-router
我想知道是否有办法在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
工作示例:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
执行此操作的最佳方法是通过路由器对象来执行此操作:
constructor(private router: Router) {
console.log(this.router.routerState.snapshot);
}
Run Code Online (Sandbox Code Playgroud)
很抱歉回答晚了,但我发现了同样的问题,并努力寻找最佳解决方案。所以我把它贴在这里供参考。
| 归档时间: |
|
| 查看次数: |
1963 次 |
| 最近记录: |