chris01
chris01

Reputation: 12331

Angular 2: Service injects service, Provider

I have a service A. That service gets another sevice B injected. So A uses B. B is used by A and injected in As construcotr.

In a component I use service A. I do not directly use service B. But A uses B because B is injected into A.

In this component I need to put

providers: [A, B]

If I only put A into providers I get

"ERROR: No provider for B" 

in the Javascript console of the browser. I do not get a compiler error.

Is there a way to hide further services that are not directly used in the components provider?

I do not like to put B into the components provider and not direclty using it.

Thanks!

EDIT

I can put all services into the module-provider and then I must not set them in any component I use a service. But is there any negative effect when doing so?

Upvotes: 1

Views: 82

Answers (1)

A. Tim
A. Tim

Reputation: 3196

Seems like you do not completely understand how DI works in Angular... Please read https://angular.io/guide/hierarchical-dependency-injection#injector-bubbling

Long story short:

  • @NgModule({providers:[]}) export class AppModule{} are available in entire application
  • @NgModule({providers:[]}) export class UserModule are available in all @Components and @Injectables that registered in current module
  • @Component({providers:[]}) are available in this component (and children, but there are some exceptions)
  • @Component({providers:[]}) creates new injector. In practice that means that if you have 3 components on your page, each one has NEW instance of injected service. I.e. in this case you do not share anything between components. That feature is rarely required...
  • When Injector resolves DI tree it searches for OWN registered @Injectables, if nothing is found, then it asks parent. So that means if you have Service1 that depends on Service2, so Service2 must be provided either in @Component or in @NgModule and Angular still will be able to resolve DI tree.
  • There is no drawbacks from putting all @Injectables into @NgModule, moreover that is "Angular way". Having individual @Component({providers:[]}) in most cases is overkill and in theory should slow your app. So use it only if you really need new instance of Service for each component.

Upvotes: 1

Related Questions