Tutorial

ng generate component messages

* Add < app-messages> in < app-component>

ng generate service message --module=app
import { Injectable } from '@angular/core';

@Injectable()
export class MessageService {
  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}

* /src/app/messages/messages.component.ts: Inject message service to display message

* src/app/messages/messages.component.html

< div *ngIf="messageService.messages.length">

  < h2>Messages< /h2>
  < button class="clear"
          (click)="messageService.clear()">clear< /button>
  < div *ngFor='let message of messageService.messages'> {{message}} < /div>

< /div>

* Other component or service: Inject message service to send a message

//Example: HeroService
...
getHeroes(): Observable {
  // Todo: send the message _after_ fetching the heroes
  this.messageService.add('HeroService: fetched heroes');
  return of(HEROES);
}