Sakuto Sakuto - 1 year ago 662
TypeScript Question

DI with cyclic dependency with custom HTTP and 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:


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):
enter image description here

My question now is, how to fix it? I've heard of
but I'm not sure I can really use it in this context.

Thanks in advance for your answer.

Answer Source

DI can't resolve cyclic dependencies. A workaround is to inject the injector and acquire the instance imperatively:

class ConfigService {
  private http: Http;
  constructor(injector Injector) {
    setTimeout(() => this.http = injector.get(Http);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download