Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject provider into another provider

Tags:

angular

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?

like image 784
Marcos J.C Kichel Avatar asked Feb 10 '16 22:02

Marcos J.C Kichel


1 Answers

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:

  • What's the best way to inject one service into another in angular 2 (Beta)?
like image 109
Thierry Templier Avatar answered Oct 03 '22 20:10

Thierry Templier