可观察对象(Observable)

最简示例:

export class AppComponent {
  title = 'angular-tour-of-heroes';
  // Create an Observable that will start listening to geolocation updates
  // when a consumer subscribes.
  locations = new Observable((observer) => {
    setTimeout(
      ()=>observer.next('hello'),
      3000
    )

    // When the consumer unsubscribes, clean up data ready for next subscription.
    return {
      unsubscribe() {
        console.log('unSubscribe...')
      }
    };
  });


  handleClick() {
    // Call subscribe() to start listening for updates.
    const locationsSubscription = this.locations.subscribe({
      next(position) {
        console.log('Current Position: ', position);
      },
      error(msg) {
        console.log('Error Getting Location: ', msg);
      }
    });

    // Stop listening for location after 10 seconds
    setTimeout(() => {
      locationsSubscription.unsubscribe();
    }, 5000);
  }

}

 

posted @ 2020-08-03 16:02  remly  阅读(164)  评论(0)    收藏  举报