角度2复位可观察定时器 [英] Angular 2 Reset Observable Timer

查看:85
本文介绍了角度2复位可观察定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务,其中有一种方法每30秒自动调用一次.我还具有一个按钮,该按钮使用户可以重置计时器,以防止再次调用此方法30秒钟.如何重置计时器,以便在单击按钮后的30秒钟内不会调用此方法?

I have a service where I have a method getting called every 30 seconds automatically. I also have a button which will allow a user to reset the timer, preventing this method from getting called for another 30 seconds. How can I reset my timer so this method won't get called within that 30 seconds if the button is clicked?

组件

constructor(private service: Service) {
  this.service.initialize();
}

refreshTimer(): void {
  this.service.refreshTimer();
}

服务

initialize(): void {
    timer(0, 30000).subscribe(() => this.refresh());
}

refreshTimer(): void {
  // Need help here
}

如您所见,我的组件从其构造函数调用initialize(),该构造函数初始化计时器以每30秒运行一次this.refresh().这个想法是我的html将在组件中调用refreshTimer(),最终将在服务中调用refreshTimer()以重新启动计时器.我该怎么办?

As you can see, my component calls initialize() from its constructor, which initializes the timer to run this.refresh() every 30 seconds. The idea is that my html will call refreshTimer() in the component, which will ultimately call refreshTimer() in the service to start the timer over. How can I do this?

提前谢谢!

推荐答案

我将使用 switchMap 取消订阅先前的 timer 并订阅新的开始所有内容的计时器再来一次.

I'd use switchMap that unsubscribes the previous timer and subscribes to the new one that start all over again.

private reset$ = new Subject();

initialize(): void {
  this.reset$
    .pipe(
      startWith(void 0),
      switchMap(() => timer(0, 30000)),
    )
    .subscribe(() => this.refresh());
}

refreshTimer(): void {
  this.reset$.next(void 0);
}

需要使用 startWith 运算符来触发在订阅时创建第一个 timer .

The startWith operator is required to trigger creating the first timer on subscription.

这篇关于角度2复位可观察定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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