角度4.3x动态http拦截器 [英] angular 4.3x dynamic http interceptor

查看:82
本文介绍了角度4.3x动态http拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注了这篇文章从媒介创建一个http拦截器,该拦截器使我可以向每个http调用添加标头

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

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

本文使用authService动态获取令牌.但是,一旦我将HttpClient注入AuthService,我就会收到循环注入错误.

The article uses the authService to get a token dynamically. However as soon as I inject HttpClient into the AuthService I get a circular injection error.

我还有其他方法可以动态调整拦截器吗?

Are there other ways i can dynamically adjust the interceptor?

推荐答案

在AngularJS和Angular中避免循环依赖的一种常规方法是就地获取另一个提供程序实例,而不是在提供程序实例上:

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<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const httpClient = injector.get(HttpClient);
    ...
  }
}

请注意,如果拦截器适用于所有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).

这篇关于角度4.3x动态http拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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