How to add HttpClient Interceptors conditionally in Angular

前端 未结 2 630
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 09:22

Recently I have been using Interceptors with Angular HttpClient.

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

2条回答
  •  臣服心动
    2021-01-04 10:14

    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(null);
    
    someHttpmethod() {
       this.interceptorTwo.next(true);
    
       // Add your CODE http
       this.myHttp.post('someUrl', data).finally(() => this.interceptorTwo.next(null));
    }
    

    yourInterceptorTwo.service.ts

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

提交回复
热议问题