每当您在页面上处于非活动状态时,我都需要暂停。让我们说你在页面上20秒没有点击它会将你重定向到主屏幕。
当前代码不适用于不活动,我不知道如何使其工作。
ngOnInit() {
// do init at here for current route.
setTimeout((router: Router) => {
this.router.navigate(['nextRoute']);
}, 20000); //20s
}
答案 0 :(得分:10)
您需要一个向后计数的计时器,并在用户操作出现时重置。要跟踪用户操作,您可以使用主机侦听器:
@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();
}
}
Stackblitz示例:https://stackblitz.com/edit/angular-2rv3or
答案 1 :(得分:2)
尝试NPM模块angular-user-idle。它可能有助于不创建自己的解决方案。
它的代码如何:
ngOnInit() {
//Start watching for user inactivity.
this.userIdle.startWatching();
// Start watch when time is up.
this.userIdle.onTimeout().subscribe(() => {
this.router.navigate(['nextRoute']);
});
}
答案 2 :(得分:0)
按照cmd安装Idlejs节点模块
npm install --save idlejs
导入模块并添加到app.component.ts
import { Idle } from 'idlejs/dist';
const idle = new Idle()
.whenNotInteractive()
.within(60)
.do(() => console.log('IDLE'))
.start();