我正在编写拦截器,这样我就不必在调用我的Web API的每个服务中处理 header 。问题在于,我的99%的 call 需要1个特定的 header 集,而其他1%的 call 只需要其中1个 header ,而无法与其他在场的 header 一起使用。众所周知,我的想法是制造2个拦截器,第一个将添加它们全部使用的1个 header ,第二个将添加其余的 header ,第二个将不包括1%。
以下是我打算如何排除1%的方法,该方法有效,但是我想看看是否有更好的方法可以解决此问题:
intercept(request: HttpRequest<any>, next:HttpHandler: Observable<HttpEvent<any>> {
let position = request.url.indexOf('api/');
if (position > 0){
let destination: string = request.url.substr(position + 4);
let matchFound: boolean = false;
for (let address of this.addressesToUse){
if (new RegExp(address).test(destination)){
matchFound = true;
break;
}
}
if (!matchFound){
...DO WORK to add the headers
}
}
最佳答案
我建议,尽管检查请求,您仍可以使用 header 添加“skip”属性,如果 header 具有skip属性,则简单地返回要求
export class CustomInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.get("skip"))
return next.handle(req);
....
}
}
您只需拨打所有您需要的 call ,即可“跳过”拦截器
this.http.get(url, {headers:{skip:"true"});