每当您在页面上处于非活动状态时,我都需要设置超时。假设您在页面上呆了 20 秒而没有点击任何内容,它会将您重定向到主屏幕。
当前的代码不适用于不活动状态,我不知道如何使其工作。
ngOnInit() {
// do init at here for current route.
setTimeout((router: Router) => {
this.router.navigate(['nextRoute']);
}, 20000); //20s
}
您需要一个可以倒计时并在用户操作发生时重置的计时器。要跟踪用户操作,您可以使用主机侦听器:
@HostListener('document:keyup', ['$event'])
@HostListener('document:click', ['$event'])
@HostListener('document:wheel', ['$event'])
resetTimer () {
// user action occured
}
计时器会是这样的:
endCount = new Subject();
// end time in minutes
private initTimer (endTime: number) {
const interval = 1000;
const duration = endTime * 60;
this.subscription = Observable.timer(0, interval)
.take(duration)
.subscribe(value => this.render((duration - +value) * interval),
err => { },
() => {
this.endCount.next();
});
}
private render (count) {
this.secondsDisplay = this.getSeconds(count);
this.minutesDisplay = this.getMinutes(count);
}
private getSeconds (ticks: number) {
const seconds = ((ticks % 60000) / 1000).toFixed(0);
return this.pad(seconds);
}
private getMinutes (ticks: number) {
const minutes = Math.floor(ticks / 60000);
return this.pad(minutes);
}
private pad (digit: any) {
return digit <= 9 ? '0' + digit : digit;
}
监听 endCount 以在用户一段时间不活动时收到通知。
重置计时器:
resetTimer (newEndTime) {
this.clearTimer();
this.initTimer(newEndTime);
}
clearTimer () {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
堆栈闪电战示例:https://stackblitz.com/edit/angular-2rv3or https://stackblitz.com/edit/angular-2rv3or
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)