No provider for ObservableDataService

2020-04-21 08:46发布

问题:

I got error with "No provider for ObservableDataService"

ObservableDataService: https://github.com/sanex3339/bannerscreator/blob/master/resources/assets/typescript/Services/ObservableDataService/ObservableDataService.ts

Service in which ObservableDataService will injected: https://github.com/sanex3339/bannerscreator/blob/master/resources/assets/typescript/Services/UploadedTemplatesService/UploadedTemplatesService.ts

I describe ObservableDataService inside 'providers' option of @Component decorator of UploadedTemplatesService.

But this error still happens. Why i still getting this error?

Important!: right now in repo for prevent this error i use global injection of ObservableDataService throug bootstrap(), but i does not need ObservableDataService as singleton.

I need UploadedTemplatesService as singleton in which new ObservableDataService will injected.

回答1:

IN fact when you implement a service you don't need to decorate it using the @Component decorator. Using the @Injectable decorator is enough.

I guess that what is a bit disturbing is that there is no way to set providers on the @Injectable decorator. The reason for this is that providers are linked to components. All the processing executed from a component will use the injector of the component.

I mean if componentA calls serviceA that calls serviceB. The @Injectable decorator will try to resolve serviceB in the componentA injector.

Another part that is important is the "hierarchical injectors" feature of Angular2. Here is an overview of all these elements and their relations with my sample:

Application
(application injector)
     |
ComponentA  --- ServiceA --- ServiceB
(component injector)

In such application, we have two injectors:

  • The application injector that can be configured using the second parameter of the bootstrap function
  • The AppComponent injector that can be configured using the providers attribute of this component. It can "see" elements defined in the application injector. This means if a provider isn't found in this provider, it will be automatically look for into this parent injector. If not found in the latter, a "provider not found" error will be thrown.

So in your case, you can define ObservableDataService within providers for the component or above. Sure defining it within bootstrap is the widest...

This question could give you more details about how hierarchical injectors of Angular work:

  • What's the best way to inject one service into another in angular 2 (Beta)?


标签: angular