import { Component , OnInit } from '@angular/core' ; import { Observable , Observer } from 'rxjs' ; class Producer { constructor ( private observer ) { } hit ( ) { this . observer . next ( 'Hit!' ) ; console . log ( `next: 'Hit!'` ) ; } stay ( ) { this . observer . next ( 'Stay' ) ; console . log ( `next: 'Stay'` ) ; } panic ( ) { this . observer . error ( 'Something bad happened' ) ; console . log ( `error: 'Something bad happened'` ) ; } done ( ) { console . log ( `complete()` ) ; this . observer . next ( 'Done listening' ) ; this . observer . complete ( ) ; } } @ Component ( { selector : 'aw-basic-02' , template : `
    <h4>02 - Error & Complete</h4>

    <div style="margin-bottom: 1rem;">
      <button type="button" (click)="producer.hit()"  >Hit me</button>
      <button type="button" (click)="producer.stay()" >Stay</button>
      <button type="button" (click)="producer.panic()">Panic</button>
      <button type="button" (click)="producer.done()" >Done</button>
      <button type="text" (click)="clear()">Clear</button>
    </div>

    <div *ngFor="let message of messages">
      {{message}}
    </div>

    <div *ngIf="errorMessage" style="background-color: red; color: white">
      OMG! We got an error!
      {{errorMessage}}!
      Time to panic!
    </div>
  ` } ) export class Basic02Component implements OnInit { errorMessage = '' ; messages : string [ ] = [ ] ; producer : Producer ; observable = new Observable ( ( o ) => { this . producer = new Producer ( o ) ; } ) ; subscriber = { next : ( value ) => this . messages . push ( value ) , error : ( err ) => ( this . errorMessage = err ) , complete : ( ) => this . messages . push ( 'Observable completed' ) } ; ngOnInit ( ) { this . observable . subscribe ( this . subscriber ) ; } clear ( ) { this . errorMessage = '' ; this . messages = [ ] ; } }