简体   繁体   中英

Angular - Reset inactivity redirection after navigating to new page

I have an Angular app, with inactivity redirection function on it, I am using code which I found here . In my app, the user is redirected to a screensaver page after 30 seconds of inactivity, so the code is almost identical (but without showing timer on screen).

Everything works great, but the issue is - that I don't want to redirect the user from some of the pages. But when I navigate from the page with redirection to the page without redirection, the timer is still alive. How to turn it off on the each navigation?


My Code:

timeout;
...
resetTimer(endTime: number = this.endTime) {
  const interval = 1000;
  const duration = endTime * 60;

  this.timerSubscription = timer(0, interval)
    .pipe(take(duration))
    .subscribe(
      value => this.render((duration - +value) * interval),
      err => {},
      () => {
        this.timeout = setTimeout(() => {
          this.navCtrl.navigateRoot(URL_CONSTANT.SCREENSAVER, {
            animated: false
          }, 100);
        });
      }
    );
}
...
ngOnDestroy() {
  this.unsubscribe$.next();
  this.unsubscribe$.complete();
  clearTimeout(this.timeout);
}

You should store a reference to the timeout, eg

this.timeout = setTimeout(() => { // Do redirect }

Then cancel the timeout when the component is destroyed (ie when the user navigates away). So add implements OnDestroy to your component class:

export class Xyz implements OnDestroy{ ... }

And add a new method called ngOnDestroy:

ngOnDestroy(){
  clearTimeout(this.timeout);
}

I've figured it out, just needed to add something like this.timerSubscription.unsubscribe();to my ngOnDestroy() .

The reason why it took me so long time to understand it - it because I was working with some modals, and there was no destroy on navigation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM