22 June 2019
Angular (9) -- Services
by Jerry Zhang
Day 18: Angular Services
Create a new service
- Create a new file named
logging.service.ts
. We don’t need to add any annotation for a service. It’s just a normal typescript class.
export class LoggingService {
logStatuseChange(status: string) {
console.log('A server status changed, new status: ' + status);
}
}
- Add a constructor to inject the service.
constructor(private loggingService: LoggingService) { }
- Give a provider
providers: [LoggingService]
- Use the service
this.loggingService.logStatusChange(accountStatus);
Hierarchical Injector
In the service provider array of each component, the provided service will affect all its descendant components.
-
AppModule: Same Instance of Service is available Application-wide
-
AppComponent: Same Instance of Service is available for all Components (but not for other Services)
-
Any other component: Same Instance of Service is available for the component and all its child components
Inject a service into another service
If we want to use a service in another service, we need to @Injectable on the service class.
@Injectable()
export class AccountsService {
constructor(private loggingService: LoggingService) {}
addAccount(name: string, status: string) {
this.accounts.push({name, status});
this.loggingService.logStatusChange(status);
}
updateStatus(id: number, status: string) {
this.accounts[id].status = status;
this.loggingService.logStatusChange(status);
}
}
Using Service for Cross-Component Communication
- Add a new EventEmitter in the service
statusUpdated = new EventEmitter<string>();
- In other classes that inject this service, we can use it.
onSetTo(status: string) {
this.accountsService.statusUpdated.emit(status);
}
- Listen to this event
In another component, we can subscribe this event and listen to it.
constructor(private loggingService: LoggingService,
private accountsService: AccountsService) {
this.accountsService.statusUpdated.subscribe(
(status: string) => alert('New Status: ' + status)
);
}