Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 redirect after inactivity

I need to make a timeout whenever you are inactive on a page. Lets say you are 20 seconds on a page without clicking something it will redirect you to the home screen.

The current code does not work for inactivity and i dont know how to make it work.

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

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

}

like image 391
Mex Avatar asked May 29 '18 08:05

Mex


2 Answers

Try NPM module angular-user-idle. It may help don't create your own solutions.

How it will look in your code:

ngOnInit() {
  //Start watching for user inactivity.
  this.userIdle.startWatching();

  // Start watch when time is up.
  this.userIdle.onTimeout().subscribe(() => {
    this.router.navigate(['nextRoute']);
  });
}

Official demo

like image 26
Max Martynov Avatar answered Oct 14 '22 18:10

Max Martynov


You need a timer which counts backwards and gets resetted when user action comes up. To track user action you can use a host listener:

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

And a timer would be something like this:

  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;
      }

Listen on endCount to get notified when user was inactive for a period of time.

To reset the timer:

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

   clearTimer () {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
   }

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

like image 198
J. S. Avatar answered Oct 14 '22 17:10

J. S.