angular 4.3x dynamic http interceptor

后端 未结 2 2008
轻奢々
轻奢々 2020-12-20 09:00

I followed this article from medium to create a http interceptor which lets me add headers to each http call

@Injectable()
export class TokenInterceptor impl         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 10:00

    A conventional way to avoid circular dependencies in both AngularJS and Angular is to get another provider instance in-place and not on provider instantiation:

    export class TokenInterceptor implements HttpInterceptor {
      constructor(public auth: AuthService, public injector: Injector) {}
      intercept(request: HttpRequest, next: HttpHandler): Observable> {
        const httpClient = injector.get(HttpClient);
        ...
      }
    }
    

    Notice that if the interceptor applies to all HttpClient requests, it will be applied to the one that is done inside the interceptor itself and likely result in infinite recursion. In order to avoid this the request can be marked to skip the interceptor (e.g. via custom header).

提交回复
热议问题