Angular 5, how to detect user inactivity

前端 未结 3 1254
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 05:57

Aside from using IdleJS and ngDoCheck(), how can we detect user inactivity in Angular 5?

Thanks

3条回答
  •  别跟我提以往
    2021-02-06 06:43

    You could try with this :

    export class AppComponent {
    
      userActivity;
      userInactive: Subject = new Subject();
    
      constructor() {
        this.setTimeout();
        this.userInactive.subscribe(() => console.log('user has been inactive for 3s'));
      }
    
      setTimeout() {
        this.userActivity = setTimeout(() => this.userInactive.next(undefined), 3000);
      }
    
      @HostListener('window:mousemove') refreshUserState() {
        clearTimeout(this.userActivity);
        this.setTimeout();
      }
    }
    

    Seems to work in this stackblitz : open the console, don't move your mouse for 3 seconds : you see the message.

    Refresh the page, move your mouse on the preview (right side) for a couple of seconds : the message doesn't pop until you stop for 3s.

    You can obviously export that into a service, because as you can see, I'm using only a class to do that.

提交回复
热议问题