问题描述
我正在尝试实现一个 ConfigService 来为项目中的正确环境检索正确的配置.我目前遇到循环依赖
I'm trying to implement a ConfigService to retrieve the right configuration for the right environment in the project. I'm currently encountering a cyclic dependancy
(index):28 Error: (SystemJS) Provider parse errors:
Cannot instantiate cyclic dependency! Http: in NgModule AppModule
Error: Provider parse errors:
我已经研究了代码,我认为存在问题:
I've explored the code and there is the problem, in my opinion:
自定义Http
constructor(backend: XHRBackend, options: RequestOptions, public spinnerService: SpinnerService, public exceptionService: ExceptionService, public configService: ConfigService)
异常服务
constructor(private _notificationService: NotificationService, private _spinnerService: SpinnerService, private _configService: ConfigService, private _router: Router)
配置服务
constructor(private http: Http) {}
如您所见,我在此图中说明了一个循环依赖项(没有任何好的约定):
As you can see, I've a cyclic dependancies illustrated in this diagram (without any good convention):
我现在的问题是,如何解决?我听说过 Injector
,但我不确定我是否真的可以在这种情况下使用它.
My question now is, how to fix it? I've heard of Injector
but I'm not sure I can really use it in this context.
预先感谢您的回答.
推荐答案
DI 无法解决循环依赖.一种解决方法是注入注入器并强制获取实例:
DI can't resolve cyclic dependencies. A workaround is to inject the injector and acquire the instance imperatively:
@Injectable()
class ConfigService {
private http: Http;
constructor(injector:Injector) {
setTimeout(() => this.http = injector.get(Http);
}
}
这篇关于具有自定义 HTTP 和 ConfigService 循环依赖的 DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!