Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 461
LoïcR Avatar asked Nov 29 '16 07:11

LoïcR


1 Answers

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);
  }
}
like image 147
Günter Zöchbauer Avatar answered Nov 09 '22 00:11

Günter Zöchbauer