如何在 Angular 中有条件地添加 HttpClient 拦截器 [英] How to add HttpClient Interceptors conditionally in Angular

查看:33
本文介绍了如何在 Angular 中有条件地添加 HttpClient 拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在使用带有 Angular HttpClient 的拦截器.

Recently I have been using Interceptors with Angular HttpClient.

我添加了与某些 HTTP GET 方法相对应的标头,而对于某些我不需要这些标头.

I add headers corresponding to some HTTP GET methods and for some I do not need those headers.

如何告诉我的拦截器有条件地将拦截器仅添加到这些方法中?我什至可以拆分服务,例如一项服务用于标头,一项服务没有标头,或者一项用于不同标头,一项用于不同标头.

How can I tell my interceptor to conditionally add interceptors to only those methods? I can even split up services like one service for headers and one without headers or one for different headers and one for different.

NgModule 提供程序

{
  provide: HTTP_INTERCEPTORS,
  useClass: AuthInterceptor,
  multi: true,
},{
  provide: HTTP_INTERCEPTORS,
  useClass: AngularInterceptor,
  multi: true,
}

MyInterceptors

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({headers: req.headers.set('X-Auth-Token', "-------------------------")});
    return next.handle(authReq);

  }
}


@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
        }
    });
  }
}

推荐答案

我知道为时已晚,我们仍然没有来自 Angular 的任何解决方案.目前一个简单的解决方法是创建一个 BehaviorSubject 并根据它的值激活拦截器.有了这个,您就可以处理必须使用拦截器的特定 HTTP 请求:

I know it is too late however, we still do not have any solution from Angular. An easy workaround at the moment is to create a BehaviorSubject and activate the Interceptor according to the value it. With this, you are able to handle specifics HTTP requests the must use your Interceptors:

yourService.service.ts

public interceptorTwo = new BehaviorSubject<boolean>(null);

someHttpmethod() {
   this.interceptorTwo.next(true);

   // Add your CODE http
   this.myHttp.post<any>('someUrl', data).finally(() => this.interceptorTwo.next(null));
}

yourInterceptorTwo.service.ts

const setAuth = this.yourService.interceptorTwo.value;
if (!setAuth) {
  return next.handle(req);
}

这篇关于如何在 Angular 中有条件地添加 HttpClient 拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆