我有一个倒计时计时器,在用户离开页面后,该计时器将继续运行。当用户离开页面时,我想破坏倒计时计时器的运行或停止它。我怎样才能做到这一点?
倒计时
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;
})
}
您可以使用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(
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句