【发布时间】: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