为某些调用禁用 Angular HttpInterceptor

Dav*_*e C 8 angular-http-interceptors angular

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

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

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

问候

戴维德

fas*_*fgs 41

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

您的服务:

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

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


Hoa*_*Son 14

您可以使用它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));
  }

....
Run Code Online (Sandbox Code Playgroud)

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