jurgenvo
jurgenvo

Reputation: 203

Angular2: Need to add provider in component for dependency on service?

I'm having some trouble understanding the logic that Angular2 uses when it comes to dependency injection. This is my situation:

app.component.ts:

import {Component} from 'angular2/core';
import {Demo1Service} from './demo-1.service';

@Component({
    selector: 'app',
    template: `<div>test template</div>`,
    providers: [Demo1Service]
})
class AppComponent {
    constructor(private _demo1Service: Demo1Service) {}
}

export {AppComponent};

demo-1.service.ts

import {Injectable} from 'angular2/core';
import {Data1Store} from './data-1.store';

@Injectable()
class Demo1Service {
    constructor(private _data1Store: Data1Store) {}
};

export {Demo1Service};

data-1.store.ts

import {Injectable} from 'angular2/core';

@Injectable()
class Data1Store {}

export {Data1Store};

http://plnkr.co/edit/4aBNbAxtHbUvVqxPRUbv?p=preview

If you run this plunker you will see that Angular needs a provider for the Data1Store to be defined in the AppComponent. In order to have some separation of concerns, I would prefer that the AppComponent doesn't need to know about the existence of the Data1Store.

Is there something I'm here?

Upvotes: 3

Views: 1585

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202146

In fact, the provider needs to present when executing the Demo1Service service. Because of hierarchical injectors, it's not mandatory to have the corresponding provider defined at the component level.

This can also be done for the whole application or within a parent injector. Defining this provider when bootstrapping your application seems to be what you need:

bootstrap(AppComponent, [ Demo1Service, Data1Store ]);

This way you don't need to define your service providers within the providers attribute of your component

Here is an overview of all these elements and there relations:

Application
     |
AppComponent  --- Demo1Service --- Data1Store

In such application, we have two 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. This question could give you more details about how hierarchical injectors of Angular work:

  • What's the best way to inject one service into another in angular 2 (Beta)?

Upvotes: 2

Related Questions