Let's say we have a Component called Comp
and two @Injectable
providers called P1
and P2
.
P1
needs an instance of P2
. P1
is injected into Comp
.
It's working perfectly if I declare both providers on Comp
like this:
@Component ({
providers: [P1, P2]
})
export class Comp { ... }
Now, what I would like to do is to declare that P1
needs P2
directly inside P1
:
@Component ({
providers: [P1]
})
export class Comp { ... }
@Injectable(/** Inject P2 here **/)
export class P1 { ... }
How to achieve this?
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:
bootstrap
functionAppComponent
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.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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With