角度自定义空闲计时器

时间:2018-02-13 11:50:20

标签: javascript angular typescript timer

嘿伙计目前我试图实现我自己的空闲计时器。我想到了一个像初始化全局事件的服务。这些重置Timer。但是我目前的实现似乎存在上下文问题,因为我无法使用'this'访问该函数。

服务:

import { Injectable } from '@angular/core';

@Injectable()
export class IdleService {

  constructor() {
           document.addEventListener("click", this.resetTimer, false);
   }

    public timeoutID:number;

     startTimer() {
        console.log("timer started");
        this.timeoutID =  setTimeout(() => {this.goInactive()}, 5000);
        console.log(this.timeoutID) 
    }

     resetTimer() {
        console.log(this.timeoutID);
        console.log("reset");
        clearTimeout(this.timeoutID);
    }

     goOffline() {
            //alert("Hey");
            console.warn("goInactive");
            // this.logout();
    }


    }

应用组件:

import { Component } from '@angular/core';
import { IdleService } from './idle.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private idleService: IdleService){
       this.idleService.startTimer();
  }
  name = 'Angular 5';
}

如果你有更好的想法如何解决这个问题,请随时告诉我。我知道Angular并不是真正为全球事件做的,但我需要这个功能。

如果你想稍微玩一下,这里也是Stackblitz。 Stackblitz

1 个答案:

答案 0 :(得分:1)

如果有人仍然感兴趣。我将eventlistener移动到一个observable,然后上下文是正确的。但我建议您查看stackblitz

如果我有真正的最终答案,我也会在这里发布。

相关问题