如何使用原生 JS 代码在 angular 中实现空闲时间?

How to implement Idle time in angular using native JS code?

我必须在我的应用程序中检测用户的空闲超时。我的应用程序同时使用原生 javascript 和 angular。 在我的 HTML + JavaScript 页面中,我在下面实现了:

<script>
var inactivityTime = function () {
    var time;
    document.onmousemove = resetTimer;
    document.onkeypress = resetTimer;
    document.onclick = resetTimer;
    document.onwheel = resetTimer;

    function callApi() {
        alert("Idle for 3 seconds. You can call your api here");
    }

    function resetTimer() {
        clearTimeout(time);
        time = setTimeout(callApi, 3000); 
        // 5 minute = 60000 * 5;
        // 1000 milliseconds = 1 second
    }
};

window.onload = function() {
  inactivityTime(); 
}
</script>

它按预期工作。

虽然我在 angular 项目中使用的是相同的代码,但 angular 代码也能正常工作,但发现了 1 个小问题 请先查看我的 angular 代码:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'project';
  time;

  ngOnInit() {  
    this.inactivityTime();  
    this.resetTimer();
  }

  inactivityTime() {
    document.onmousemove = this.resetTimer;
    document.onkeypress = this.resetTimer;
    document.onclick = this.resetTimer;
    document.onwheel = this.resetTimer;

  }

  resetTimer() {
    clearTimeout(this.time);
    this.time = setTimeout(() => {
      alert('Idle for 3 seconds. You can call your api here');
    }, 3000);
  }
}

我面临的问题是 - 在页面加载时,即使正在移动鼠标/按键,也会调用警报。之后一切都按预期工作。但是在页面加载时它不起作用。

在此请求帮助。

谢谢!

最好的方法是使用 Angular HostListener 装饰器并将其绑定到文档:

export class AppComponent {
  time: number;

  ngOnInit() {  
    this.resetTimer();
  }

  @HostListener('document:mousemove')
  @HostListener('document:keypress')
  @HostListener('document:click')
  @HostListener('document:wheel')
  resetTimer() {
    clearTimeout(this.time);
    this.time = setTimeout(() => {
      alert('Idle for 3 seconds. You can call your api here');
    }, 3000);
  }
}

Here is solution in stackblitz

最简单的选择是使用 angular-user-idle.

https://www.npmjs.com/package/angular-user-idle

将此包含在 app.module.ts 中: 进口:[ .. .. UserIdleModule.forRoot({空闲: 3, 超时: 0, ping: 0}) ]

app.component.ts

ngOnInit() {  
    this.userIdle.startWatching();
    this.userIdle.onTimerStart().subscribe(count =>{
      console.log(count);
      if(count == 3){
        alert('Idle for 3 seconds. You can call your api here');
        this.userIdle.resetTimer();
      }
    });
  }

  @HostListener('document:keyup', [])
  @HostListener('document:click', [])
  @HostListener('document:wheel', [])
  @HostListener('document:mousemove', [])
  restart() :void{
    this.userIdle.resetTimer();
  }