我有一个Angular应用,上面有不活动重定向功能,我使用的代码是我找到的。此处.在我的应用程序中,用户在30秒不活动后会被重定向到屏幕保护页面,所以代码几乎相同(但不在屏幕上显示计时器)。
一切都很好,但问题是--我不想将用户从一些页面重定向.但当我从有重定向的页面导航到没有重定向的页面时,计时器仍然有效。如何在每次导航时关闭它?
我的代码。
timeout;
...
resetTimer(endTime: number = this.endTime) {
const interval = 1000;
const duration = endTime * 60;
this.timerSubscription = timer(0, interval)
.pipe(take(duration))
.subscribe(
value => this.render((duration - +value) * interval),
err => {},
() => {
this.timeout = setTimeout(() => {
this.navCtrl.navigateRoot(URL_CONSTANT.SCREENSAVER, {
animated: false
}, 100);
});
}
);
}
...
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
clearTimeout(this.timeout);
}
你应该存储一个超时的引用,比如说。
this.timeout = setTimeout(() => { // Do redirect }
然后在组件被销毁时(即用户导航离开时)取消超时.所以在你的组件类中添加实现OnDestroy。
export class Xyz implements OnDestroy{ ... }
然后添加一个新的方法叫做ngOnDestroy:
ngOnDestroy(){
clearTimeout(this.timeout);
}
我已经想好了,只是需要添加一些类似于 this.timerSubscription.unsubscribe();
对我 ngOnDestroy()
.
我之所以花了这么长时间才明白--是因为我在使用一些模态,而导航上没有 destroy。