简体   繁体   中英

Angular Custom Idle Timer

Hey guys currently i try to implement my own idle Timer. I thought of something like a service where you initialize the Global events. These reset the Timer. But with my current implementation there seems to be a context problem because i cant access the function with 'this'.

Service:

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();
    }


    }

App Component:

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';
}

if you got better ideas on how to solve this feel free to tell me. I know that Angular isnt really made for global events but i need this feature.

Here is also a Stackblitz if you want to play around with it a little bit. Stackblitz

if anyone is still interested. I moved the eventlistener to an observable and after that the context is right. But i would just recommend you to have a look at the stackblitz .

if i have the really final answer i will post that here too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM