I have an Angular2
app with a service
that is used for getting a data from an API. Following this example, I want to create a separate file which should contain some configuration data. My problem is that my service has an @Injectable()
decorator and I'm not sure if I can pass it a provide
array in the metadata in which I will inject the configuration as shown in the tutorial. Anybody ever faced such a problem is welcome to share his solution :)
In fact, Angular2 leverages hierarchical injectors and injectors are linked to components. In short you can define providers only on components (providers
property) or at application level (bootstrap
function).
Regarding services, they will be able to use providers that are visible for the component that initiated the call but you can't define providers at their levels.
Here is a sample:
Application
|
AppComponent
|
ChildComponent
getData() --- Service1 --- Service2
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 means that when trying to inject the Service1
into the ChildComponent
constructor, Angular2 will look into the ChildComponent
injector, then into the AppComponent
one and finally into the application one.
Since Service2
needs to be injected into Service1
, the same resolution processing will be done: ChildComponent
injector, AppComponent
one and application one.
This means that both Service1
and Service2
can be specified at each level according to your needs using the providers
attribute for components and the second parameter of the bootstrap
function for the application injector.
This answer could help you:
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