Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - inject into @Injectable

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 :)

like image 234
Radoslav Stoyanov Avatar asked Mar 14 '23 04:03

Radoslav Stoyanov


1 Answers

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:

  • 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 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:

  • What's the best way to inject one service into another in angular 2 (Beta)?
like image 183
Thierry Templier Avatar answered Mar 19 '23 09:03

Thierry Templier