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
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With