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

ACh*_*han 4 javascript setinterval cleartimeout angular

我必须在我的应用程序中检测用户的空闲超时。我的应用程序同时使用本机 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>
Run Code Online (Sandbox Code Playgroud)

它正在按预期工作。

虽然我在角度项目中使用的相同,角度代码也可以工作,但观察到 1 个小问题,请先查看我的角度代码:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

在此请求帮助。

谢谢你!

Mar*_*ski 8

The best approach is to use Angular HostListener decorator and bind it to document:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Here is solution in stackblitz