2017-08-25 63 views
1

我有一个倒数计时器,在用户离开页面后继续运行。当用户离开页面时,我想销毁倒计时器从运行或停止它。我怎样才能做到这一点?如何销毁/停止可观察间隔

countdown.ts

public time: number; 
public countDown:Observable<any>; 
public currentUnix; 

constructor() { 
    this.currentUnix = moment().unix(); 
    this.time = moment(1503773977000).unix() - this.currentUnix; 
} 


ngOnInit() { 
    this.countDown = Observable.interval(1000) 
     .map(res => { 
     return this.time = this.time - 1 
     }) 
     .map(res => { 

     let timeLeft = moment.duration(res, 'seconds'); 
     let string: string = ''; 

     // Days. 
     if (timeLeft.days() > 0) 
      string += timeLeft.days() + ' Days'; 

     // Hours. 
     if (timeLeft.hours() > 0) 
      string += ' ' + timeLeft.hours() + ' Hours'; 

     // Minutes. 
     if (timeLeft.minutes() > 0) 
      string += ' ' + timeLeft.minutes() + ' Mins'; 

     // Seconds. 
     string += ' ' + timeLeft.seconds(); 
     console.log("string", string); 
     return string; 
     }) 
} 

回答

3

您可以使用takeUntil运算符。

import { Subject } from 'rxjs/Subject'; 
import 'rxjs/add/operator/takeUntil'; 

... 

private onDestroy$ = new Subject<void>(); 

ngOnDestroy(): void { 
    this.onDestroy$.next(); 
} 

ngOnInit() { 
    this.countDown = Observable.interval(1000) 
           .takeUntil(this.onDestroy$) // <---- 
           .map(
... 
0

您必须已创建基于您this.countDown一个subscrtiption,您可以在ngOnDestroy摧毁它,

摘自documentation

认沽清理逻辑ngOnDestroy(),必须在 之前运行的逻辑破坏指令。

.... 
this.subscription = this.countDown.subscribe(...) 
... 

public ngOnDestroy() { 
    this.subscription.unsubscribe(); 
} 

希望这有助于!

+0

我没有在我的代码中的任何地方订阅 – derrickrozay