Angular 2 Dependency Injection - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki
Inject the service
export class EventService {
public getEvents() {
return EVENTS;
}
}
- Add the service into providers of module
@NgModule({
providers: [EventService],
}
- Inject the service into the component
export class EventsListComponent implements OnInit {
public events: any[];
private eventList: EventService
// EventService is injected through constructor
constructor(private eventList: EventService) {
}
// OnInit method is called when the component is initialized.
public ngOnInit() {
this.events = this.eventList.getEvents();
}
}
Note: When injector is asked for an instance of EventsListComponent, it will create an instance of EventService then create EventsListComponent instance with this EventService instance.
Dependency Injection
How many instances of a service is created for each component? Singleton
Hierarchical Injector: providers may be set up in different 'level' - single instance is used for that level.
- Component level: A single service instance is used for each component instance.
@Component({
//...
providers: [MyService]
});
If the component contains child components and these child components need MyService, a single instance of MyService is used for all child components.
- Module: a single service instance is used for all instances that depend on the service.
@NgModule({
//...
providers: [MyService]
});
Token
Token are used for defining different dependencies
- Token is a string
@NgModule({
//...
providers: [
{ provide: 'MyService', useClass: MyService },
{ provide: 'MyService1', useClass: MyService }
]
});
For each token, Injector will return a single MyService instance.
- Token is a type
@NgModule({
//...
providers: [
MyService,
{ provide: MyService, useClass: MyService }
]
});
- Use Token for injection
class MyComponent {
constructor(@Inject("MyService") myService) {
}
}
Factory method
Define factory method for Injector to create instance.
const IS_PROD = false;
providers: [
// we provide a factory
{
provide: RaceService,
useFactory: () => IS_PROD ? new RaceService(apiService) : new FakeRaceService(),
deps: [ApiService]
}
Notes:
- We need to create the instance explicitly.
- deps: define the dependencies.