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 s
It is a bit strange, but only components can configure dependency injection in Angular (well, and bootstrap()
, but that is essentially the same as the root component). I.e., only components can specify providers.
As @Thierry mentions in his answer, each component in the component tree will get an associated "injector" if the component has a providers
array specified. We can think of this like an injector tree, that is (normally much) sparser than the component tree. When a dependency needs to be resolved, this injector tree is consulted. The first injector that can satisfy the dependency does so. The injector tree is walked up, toward the root component/injector.
So, in order for your service to inject a configuration object dependency, that config object first has to be registered with an injector. I.e., in a component's providers
array, call
provide(stringToken or OpaqueToken, {useValue: MyConfigObject} )
This registration must occur somewhere at or above the component where you want to use/inject your service.
Your service should then be able to @Inject
the registered config object, because it will find it in the injector tree.
Note, since only components can configure providers, the @Injectable()
decorator does not support any configuration options, so a providers
array is not supported.