Jerry's Blog

Recording what I learned everyday

View on GitHub


22 June 2019

Angular (9) -- Services

by Jerry Zhang

Day 18: Angular Services

Create a new service

export class LoggingService {
  logStatuseChange(status: string) {
    console.log('A server status changed, new status: ' + status);
  }
}
constructor(private loggingService: LoggingService) { }
providers: [LoggingService]
this.loggingService.logStatusChange(accountStatus);

Hierarchical Injector

In the service provider array of each component, the provided service will affect all its descendant 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

statusUpdated = new EventEmitter<string>();
onSetTo(status: string) {
    this.accountsService.statusUpdated.emit(status);
  }

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)
    );
}
tags: Angular