最简示例:
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); } }