der*_*zay 5 ionic-framework angular
我有一个倒数计时器,在用户离开页面后继续运行.当用户离开页面时,我想要销毁倒数计时器或停止它.我怎样才能做到这一点?
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;
})
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*kij 10
你可以使用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(
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3789 次 |
| 最近记录: |