Angular 拦截器排除特定的 url

dmo*_*181 7 javascript typescript angular

我正在编写拦截器,这样我就不必处理调用我的 web api 的每个服务中的标头。问题在于我的 99% 的调用需要 1 个特定的标题集,但其他 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
    }
  }
Run Code Online (Sandbox Code Playgroud)

Eli*_*seo 30

从 Angular 12更新,使用“上下文”,请参阅此SO

我建议,尽管检查请求,您可以使用标头添加“跳过”属性,如果标头具有跳过属性,则简单地返回请求

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

并且您进行所有需要“跳过”拦截器的调用,例如

this.http.get(url, {headers:{skip:"true"});
Run Code Online (Sandbox Code Playgroud)


Iho*_*ran 14

req.headers.get("skip")按照 Eliseo 的建议进行检查后,我建议从请求中删除此标头,因为它仅与 Angular 相关,不应将其传输到 API(实际上它可能会导致问题)

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

if (skipIntercept) {
    request = request.clone({
        headers: request.headers.delete('skip')
    });
}
Run Code Online (Sandbox Code Playgroud)


dmo*_*181 11

我最终要做的是拥有一个我不想在拦截器中使用的 url 数组(采用正则表达式格式),如下所示:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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

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

  constructor(backend: HttpBackend) {
    this.customHttpClient = new HttpClient(backend);
  }
}
Run Code Online (Sandbox Code Playgroud)

customHttpClient 实例不会使用拦截器。