为某些调用禁用 Angular HttpInterceptor

Disable Angular HttpInterceptor for some call

我有一个带有 HttpInterceptor 的 angular 应用程序,它捕获 http 错误以显示一些对话框,这对我的所有应用程序都是通用的。

我想为某些特定调用禁用拦截器,但我更喜欢禁用调用 http 的默认行为,而不是将异常写入拦截器。 有人发现这个问题吗?

如果需要,我可以举个例子更具体。

此致

大卫

您可以使用 HttpBackend 来执行此操作。

描述:注入时,HttpBackend直接将请求分派到后端,不经过拦截器链。

使用: 您可以像 HttpClient 一样使用,方法是从 @angular/common/http

导入它

示例:

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

...

@Injectable({
  providedIn: 'root'
})
export class HttpHelperService {

  private httpClient: HttpClient;

  constructor( httpBackend: HttpBackend) { 
     this.httpClient = new HttpClient(httpBackend);
  }

  // use like normal with HttpClient. However, should name it carefully to separate which http request go throught interceptor and which is not
  put(path: string, body: Object = {}): Observable<any> {
    return this.httpClient.put(
      `${this.URL}${path}`,
      JSON.stringify(body)
    ).pipe(catchError(this.formatErrors));
  }

....

参考:https://angular.io/api/common/http/HttpBackend

使用 Angular 12,现在可以在您的调用中包含一些元数据(使用 HttpContext),可以在拦截器中使用这些元数据来制作决定(或任何你真正想要的)。

例子

你的拦截器:

export const BYPASS_LOG = new HttpContextToken(() => false);

export class MyLogInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.context.get(BYPASS_LOG) === true)
      return next.handle(req);

    console.log(`req to ${req.url}`);

    return next.handle(req);
  }
}

您的服务:

httpClient.get('https://example.com/', { context: new HttpContext().set(BYPASS_LOG, true) });

您可以查看 angular 文档以获取更多信息: