Circular dependency injection angular 2

感情迁移 提交于 2019-11-27 05:16:58

You can workaround circular dependencies by injecting Injector instead of one of the services that cause the circular dependency

private payrollService:PayrollService;
constructor(/*private payrollService:PayrollService*/ injector:Injector) {
  setTimeout(() => this.payrollService = injector.get(PayrollService));
}

In my case (Angular 4 in an Ionic project) even injecting the service just before it's usage (upon user interaction) was not working (Same "Can't resolve all parameters..." at startup).

What worked for me was to inject (and thus provide) the service by name.

So in my app module :

...
providers: [{provide: "MyServiceName", MyServiceClass}],
...

And when needed :

const myService: MyServiceClass = injector.get("MyServiceName");
...

I know the post is old but thanks anyways above solution has worked for me as i had cyclic dependency problem so i have to use injector to avoid creating mediator service to communicate, Although one correction in above solution

From Angular 5 onwards we need to use:

providers: [{provide: "MyServiceName",useclass: MyServiceClass}],

and then

injector.get('MyServiceName')

although get is derpecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!