问题描述
我正在尝试实现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:
CustomHttp
CustomHttp
constructor(backend: XHRBackend, options: RequestOptions, public spinnerService: SpinnerService, public exceptionService: ExceptionService, public configService: ConfigService)
ExceptionService
ExceptionService
constructor(private _notificationService: NotificationService, private _spinnerService: SpinnerService, private _configService: ConfigService, private _router: Router)
ConfigService
ConfigService
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!