Inject a service into another service

前提是你 提交于 2019-12-25 07:16:17

问题


I would like to inject a service into another service but, for some reason, the "@Inject" decorator is being ignored. For example, the following service depends on another service:

@Injectable()
class MyService {
    final AnotherService _service;
    MyService(@Inject(AnotherService) this._service);
// ... more methods
}

Angular2 throws the following error:

ORIGINAL EXCEPTION: No provider for AnotherService!

Am I using the "@Inject" decorator in a bad way?


回答1:


Some information is missing to fully solve this but exception says that the injector doesn't have enough information to resolve AnotherService

The DI in angular is build upon hierarchies, starting from the root injector which is created upon an angular application bootstrap.

Each hierarchy is a new injector instance, resolving a dependency is done from bottom to top, i.e: if an injector can't resolve it will ask its parent to resolve. This will go on until it reach an injector without a parent (root injector).

Make sure you declare a provider for AnotherService before you declare a provider for MyService.

Just add a provider to AnotherService in the providers array you supply to bootstrap.



来源:https://stackoverflow.com/questions/38295702/inject-a-service-into-another-service

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