In fact, injectors can be only configured at the component level or when bootstrapping the application.
When you set providers at the component level, every classes involved in the processing will have a access to these providers: sub components, services. But you can't configure providers for services themselves.
If you configure providers at the bootstrap level (when calling the bootstrap
function), all elements in the application will be able to use these providers.
In fact, dependency injector of Angular2 leverages hierarchical injectors. This means that if the provider isn't found at a level, it will be look for in the level above and so on.
Here is an overview of all these elements and there relations:
Application
(providers defined in bootstrap)
|
AppComponent
(providers defined in the providers attribute)
|
ChildComponent
(providers defined in the providers attribute)
getData() --- Service1 --- Service2
To be able to use Service2
in Service1
, the corresponding provider must be found in the providers tree.
In such application, we have three 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.
- The
ChildComponent
injector that will follow the same rules than the AppComponent
one. To inject elements involved in the injection chain executed forr the component, providers will be looked for first in this injector, then in the AppComponent
one and finally in the application one.
This answer could give you more details about the hierarchical injectors: