不活动后角度4重定向

Mex*_*Mex 8 typescript angular

每当您在页面上处于非活动状态时,我都需要暂停.让我们说你在页面上20秒没有点击它会将你重定向到主屏幕.

当前代码不适用于不活动,我不知道如何使其工作.

ngOnInit() {
// do init at here for current route.

setTimeout((router: Router) => {
    this.router.navigate(['nextRoute']);
}, 20000);  //20s
Run Code Online (Sandbox Code Playgroud)

}

J. *_* S. 15

您需要一个向后计数的计时器,并在用户操作出现时重置.要跟踪用户操作,您可以使用主机侦听器:

 @HostListener('document:keyup', ['$event'])
 @HostListener('document:click', ['$event'])
 @HostListener('document:wheel', ['$event'])
 resetTimer () {
    // user action occured
  }
Run Code Online (Sandbox Code Playgroud)

计时器将是这样的:

  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;
      }
Run Code Online (Sandbox Code Playgroud)

监听endCount,以便在用户处于非活动状态一段时间后收到通知.

要重置计时器:

resetTimer (newEndTime) {
    this.clearTimer();
    this.initTimer(newEndTime);
  }

   clearTimer () {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
   }
Run Code Online (Sandbox Code Playgroud)

Stackblitz示例:https://stackblitz.com/edit/angular-2rv3or