问题描述
我正在编写拦截器,这样我就不必在调用我的Web api的每个服务中处理标头.问题是我的99%的呼叫需要1个特定的标头集,而其他1%的呼叫只需要其中1个标头,并且无法与其他存在的标头一起使用.知道这一点后,我的想法是制作2个拦截器,第一个将添加它们全部使用的1个标头,第二个将添加其余的标头,第二个将不包含1%的标头.
I am writing interceptors such that I don't have to handle the headers in every service calling my web api. The problem with this is that 99% of my calls require 1 specific set of headers, but the other 1% only require 1 of the headers and will not work with the others present. With this being known my idea is to make 2 interceptors, the first will add the 1 header that they all use and the second will add the rest of the headers, with the second excluding the 1%.
以下是我打算排除1%的方法的方法,该方法可以正常工作,但是我想看看是否有更好的方法可以解决此问题:
The following is how I am going about excluding the 1%, which works, but I want to see if there is a better way of going about this:
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
}
}
推荐答案
我最后要做的是拥有一个我不想在拦截器中使用的url数组(以Regex格式):
What I wound up doing is having an array of urls (in Regex Format) that I did not want to be used in the interceptor like so:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AddCustomHeadersInterceptor implements HttpInterceptor {
urlsToNotUse: Array<string>;
constructor(
) {
this.urlsToNotUse= [
'myController1/myAction1/.+',
'myController1/myAction2/.+',
'myController1/myAction3'
];
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.isValidRequestForInterceptor(request.url)) {
let modifiedRequest = request.clone({
setHeaders: {
//DO WORK HERE
}
});
return next.handle(modifiedRequest);
}
return next.handle(request);
}
private isValidRequestForInterceptor(requestUrl: string): boolean {
let positionIndicator: string = 'api/';
let position = requestUrl.indexOf(positionIndicator);
if (position > 0) {
let destination: string = requestUrl.substr(position + positionIndicator.length);
for (let address of this.urlsToNotUse) {
if (new RegExp(address).test(destination)) {
return false;
}
}
}
return true;
}
}
这篇关于角拦截器排除特定的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!