【问题标题】:Inject http client into HTTP Interceptor Angular 4将http客户端注入HTTP拦截器Angular 4
【发布时间】:2018-05-17 01:47:09
【问题描述】:

如何将http client 注入HTTP Interceptor?每当我这样做时,它都会抛出:Uncaught Error: Provider parse errors: Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

我的interceptor 看起来像:

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

  constructor(private ehs: ErrorHandlerService,
              private localStorageService: LocalStorageService,
              private router: Router,
              private http: HttpClient
             ){}

【问题讨论】:

  • 不要在你的拦截器中使用 HttpClient。使用服务。然后在 CustomHttpInterceptor 中使用 Injector 注入服务,例如stackoverflow.com/questions/47417899/…
  • 成功了,顺便说一句,为什么这个解决方案有效而我的无效?
  • 不知道能不能注入HttpClient as const http = this.inj.get(HttpClient);.(没试过)只是喜欢代码少的拦截器可能
  • 是的,但是你不能将带有 HttpClient 的服务注入到 Http 拦截器中。它会引发与我在问题中提供的完全相同的错误。为什么?
  • 在 DI 期间构建 HttpClient 实例如下所示:new HttpClient(arrayOfHttpInterceptors)。当您尝试将 HttpClient 注入其中一个拦截器时,它无法工作,因为客户端和拦截器都必须等待另一个拦截器首先构建。但是,您可以在运行时通过注入器获取其中任何一个,因为它们在实例化期间不会相互依赖。

标签: angular angular-http-interceptors


【解决方案1】:

你可以使用注射器

  constructor(inj: Injector) {
    this.auth = inj.get(AuthService)
  }

看这个例子: https://plnkr.co/edit/8CpyAUSJcCiRqdZmuvt9?p=preview

https://angular.io/api/core/Injector

关于这个问题的长篇讨论:https://github.com/angular/angular/issues/18224

【讨论】:

    猜你喜欢
    • 2017-11-07
    • 2018-05-19
    • 1970-01-01
    • 2015-11-30
    • 2014-02-09
    • 2018-07-08
    • 1970-01-01
    • 2018-03-30
    • 2023-03-13
    相关资源
    最近更新 更多