using services & dependency injection
service handles a generic task e.g. logging
a service is just a class
only components and directives need to be registered
export class LoggingService{
logStatusChange(status: string){
console.log('A server status changed. New status : ' + status);
}
}
>
Top
Index
injecting a service into components
hierarchical injector
- import the class
- add the providers property to the component directive if necessary
- add the type to the providers property
- add instance of the type as a c'tor argument
import { Component, EventEmitter, Output } from '@angular/core';
import {LoggingService } from '../logging.service';
@Component({
...
providers: [LoggingService]
})
export class NewAccountComponent {
...
constructor(private loggingService: LoggingService){}
...
}
Top
Index
understanding the hierarchy injector
hierarchical injector
Angular DI creates a type instance for a component and its children will all use
the same instance
- AppModule - same instance of service is available app-wide
- AppComponent - same instance of service is available for all Components (only components)
-
Any other component - same instance of service is available for the component and
its children
Top
Index
number of service instances
a service in a component decorator's provider property will be used as a single
instance when injected to child components
the exception is if a child component decorator's provider property declares the
service, the child component will get its own instance of the injected service
Top
Index
injecting services into services
putting a service in the AppModule decorator's providers property lets the entire
app use a single instance of the service
override behavior by declaring service in another component or module decorator's
providers property
for a service to be injected with another service the Injectable decorator is used
import { Injectable } from '@angular/core';
...
@Injectable()
export class AService {
...
constructor(private loggingService: LoggingService) { }
...
}
Top
Index
using services for cross-component communication
service has an EventEmitter
...
@Injectable()
export class AService {
...
statusUpdated = new EventEmitter<string>();
...
}
service is injected into component
component uses service methods to fire events
...
export class AComponent {
constructor(private aService: AService) { }
onSetTo(status: string) {
this.aService.update(this.id, status);
this.aService.statusUpdated.emit(status);
}
}
another component is injected with the service
in c'tor the component subscribes to the service's event
...
export class BComponent {
constructor(private aService: AService) {
// subscribe to the event
this.aService.statusUpdated.subscribe(
// display a message box describing the new status
(status: string) => alert('New status : ' + status)
);
}
...
}
Top
Index
using a service for "Push Notification"
same as above but the service calls its EventEmitter's emit method
Top
Index