我正在尝试实现ConfigService以检索项目中正确环境的正确配置。我目前遇到循环依赖
(index):28 Error: (SystemJS) Provider parse errors:
Cannot instantiate cyclic dependency! Http: in NgModule AppModule
Error: Provider parse errors:
我已经探索了代码,在我看来存在问题:
CustomHttp
constructor(backend: XHRBackend, options: RequestOptions, public spinnerService: SpinnerService, public exceptionService: ExceptionService, public configService: ConfigService)
ExceptionService
constructor(private _notificationService: NotificationService, private _spinnerService: SpinnerService, private _configService: ConfigService, private _router: Router)
的ConfigService
constructor(private http: Http) {}
正如你所看到的,我在这个图中说明了一个循环依赖(没有任何好的约定):
我现在的问题是,如何修复它?我听说过Injector
,但我不确定我是否真的可以在这种情况下使用它。
提前感谢您的回答。
答案 0 :(得分:28)
DI无法解决循环依赖关系。解决方法是注入注入器并强制获取实例:
@Injectable()
class ConfigService {
private http: Http;
constructor(injector:Injector) {
setTimeout(() => this.http = injector.get(Http);
}
}