typescript Angular拦截器排除特定URL

qxgroojn  于 2023-05-01  发布在  TypeScript
关注(0)|答案(7)|浏览(154)

我正在编写拦截器,这样我就不必处理每个调用我的web API的服务中的头。这样做的问题是,99%的调用需要1个特定的头集,但其他1%只需要其中一个头,并且无法与其他现有的头一起工作。有了这个,我的想法是做2个拦截器,第一个将添加他们都使用的1头,第二个将添加其余的头,第二个排除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
    }
  }
shstlldc

shstlldc1#

更新从Angular 12开始,使用context,参见此SO

我建议,尽管检查请求,你可以使用头部添加一个“跳过”属性,如果头部有跳过属性,简单地返回请求

export class CustomInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.headers.get("skip"))
           return next.handle(req);
      
        ....
    }
}

而你打所有你需要的电话“跳过”拦截器就像

this.http.get(url, {headers:{skip:"true"}});
7ajki6be

7ajki6be2#

在按照Eliseo的建议检查了req.headers.get("skip")之后,我建议从请求中删除这个头,因为它只与Angular相关,不应该传输到API(实际上它会导致问题)

const skipIntercept = request.headers.has('skip');

if (skipIntercept) {
    request = request.clone({
        headers: request.headers.delete('skip')
    });
}
z2acfund

z2acfund3#

我最终做的是有一个url数组(Regex),我不想在拦截器中使用,如下所示:

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;
  }
}
iszxjhcz

iszxjhcz4#

在默认情况下创建时,HttpClient将使用拦截器。如果你想避免这种情况,你可以使用构造函数创建另一个HttpClient示例。

@Injectable()
class Service {
  private customHttpClient: HttpClient;

  constructor(backend: HttpBackend) {
    this.customHttpClient = new HttpClient(backend);
  }
}

customHttpClient示例将不使用拦截器。

wribegjk

wribegjk5#

您可以尝试扩展HttpClient而不是使用Interceptor。
Interceptor World中,每个请求在执行之前都会被停止-消息(添加头部)。
HttpClient World中,在Client对象示例化时会注意这一点。
如果您认为有必要,您可以考虑使用不同的变体本身,HttpClient 99 Percent变体,HttpClientOnePercent变体等。
下面的链接可以给予你一个良好的开端:
https://medium.com/@admin_87321/extending-angular-httpclient-6b33a7a1a4d0

deikduxw

deikduxw6#

更新Андрей Керничный's answer

import { Injectable } from '@angular/core';
import { HttpClient, HttpBackend } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class CartService {
  private customHttpClient: HttpClient;

  constructor(private http: HttpClient, backend: HttpBackend) { 
    this.customHttpClient = new HttpClient(backend);
  }

  getZohoItems() {
    // call zoho url
    return this.customHttpClient.get('http://zoho.com/api/orders/');
  }

  getItems() {
    // call localhost:8000 url
    return this.http.get('/api/orders/');
  }
}
liwlm1x9

liwlm1x97#

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.indexOf('Url that you want to hide') === -1) {
  this.spinner.show();
  return next.handle(req).pipe(
    finalize(() => this.spinner.hide())
  );
}
if (req.url.indexOf('Url that you want to hide') !== -1) {
  this.spinner.hide();
}
return next.handle(req);

}

相关问题