Sakuto Sakuto - 3 days ago 5
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:

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) {}


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
Injector
but I'm not sure I can really use it in this context.

Thanks in advance for your answer.

Answer

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);
  }
}
Comments