Angular 5, how to detect user inactivity

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

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

Thanks

3条回答
  •  -上瘾入骨i
    2021-02-06 06:56

    This solution worked fine for me. the problem I faced with the accepted answer is, it only focuses on mouse events and no keyboard keypress events

        userActivity;
        userInactive: Subject = new Subject();
    
        constructor( ) {
            
            this.setTimeout();
            this.userInactive.subscribe(() => {
            this.router.navigate(['/auth/lock']);
            });
           
            }
    
    • These events check if user is idle for a specific time and then subscribe to a different ( lock ) screen

       keyPress(event: KeyboardEvent): void {
           clearTimeout(this.userActivity);
           this.setTimeout();
       }
       setTimeout(): void {
           this.userActivity = setTimeout(() => this.userInactive.next(undefined), 900000);
       }
      
       @HostListener('window:mousemove') refreshUserState() {
           clearTimeout(this.userActivity);
           this.setTimeout();
       }
      

提交回复
热议问题