事件发生后在角度2中重置计时器 [英] Reset timer after event in angular 2

查看:46
本文介绍了事件发生后在角度2中重置计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在闲置15分钟会话后实施注销,而不使用第3方lib或ngrx. 我已经创建了一项服务:

I am implementing logout after 15 mins idle session without using 3rd party lib or ngrx. I have created a service:

run(){
    window.onload = () => {this.startTimer()};
    window.onmousemove = () => {this.resetTimer()};
}

startTimer(){
    let ticks = Observable.timer(0, 1000);
    return ticks
}
resetTimer(){
    // code here
}

sessionTimeOut(){
    // logic to logout
    this.resetTimer().subscribe(val =>{console.log(val)}
}

我使用一些rxjs函数创建的方法很少,到目前为止它们都没有起作用,是否可以在resetTimer()方法上获得一些帮助?谢谢.

I have create few approach using some rxjs functions, none of them has worked so far, Is it possible to get some help on resetTimer() method? thank you.

推荐答案

您可以在mousemove事件上使用switchMap重新启动计时器,该路由消除了跟上计时器值的需要,只需将15000插入设置并忘记.

You could use switchMap on your mousemove event to restart the timer, this route removes the need to keep up with the timer values and just plug 15000 in to set and forget.

const newTimer = () => Rx.Observable.timer(3000);
const mouseMove = Rx.Observable.fromEvent(document, 'mousemove')
    .startWith("loaded")
    .throttleTime(250);
const logOut = mouseMove.switchMapTo(newTimer());

logOut.subscribe(() => console.log('logout'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.min.js"></script>

move mouse around here to not log out

从下面请求发出的注释中,我假设是每秒,并且将值重置为mousemove.

From the comments below requesting emits, I assumed to be every second, with the value resetting on mousemove.

const mouseMove = Rx.Observable.fromEvent(document, 'mousemove')
  .startWith("loaded")
  .throttleTime(250)
  .do(() => console.log("restart timer"));
const newTimer = () => {
  console.log("starting timer");
  return Rx.Observable.timer(0, 1000);
};
const timer = mouseMove.switchMapTo(newTimer());

timer.subscribe(v => console.log(v));

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.min.js"></script>

这篇关于事件发生后在角度2中重置计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆