【问题标题】:rxjs countdown that triggers method触发方法的rxjs倒计时
【发布时间】:2021-10-24 08:19:28
【问题描述】:

我正在尝试进行 5 分钟倒计时,以触发服务方法并重新加载 5 分钟倒计时(基本上我正在尝试每 5 分钟重新加载一些数据)

  constructor(
    private reloadDataService: ReloadDataService,
    private userService: UserService
    ) {
      this.timer$ = timer(0, 1000).pipe(
        scan(acc => --acc, 300),
        takeWhile(x => x >= 0),
      );
    }

realod 方法由按钮触发或每 5 分钟触发一次

  reload() {
    this.lastRefresh = new Date();
    this.reloadDataService.reload()
  }

  ngOnInit() {
    this.getUserDetails();
  }

我试过了

this.timer$ = timer(0, 1000).pipe(
            switchMap(() => this.reload()),
            scan(acc => --acc, 300),
            takeWhile(x => x >= 0),
          );

但没有用 - 如何每 5 分钟触发一次重新加载方法?

【问题讨论】:

  • 你能不能把计时器设置为每 5 分钟重复一次而不是每 1 秒重复一次?

标签: javascript angular timer rxjs


【解决方案1】:

一种方法是使用 rxjs 提供的间隔或计时器功能。

这是我创建的一个示例。

countDown: Subscription = null;
minutes: number = 5;
counter: number = this.minutes * 60;
triggered: number = 0;

启动定时器功能

startTimer(): void {
  this.countDown ? this.stopTimer() : null;
  this.countDown = interval(1000).subscribe(() => {
    --this.counter;
    if (!this.counter) {
      this.trigger();
    }
  });
}

停止计时功能

stopTimer(): void {
  if (this.countDown) {
    this.countDown.unsubscribe();
    this.countDown = null;
  }
}

倒计时结束时触发函数

trigger(): void {
  this.counter = this.minutes * 60;
  this.stopTimer(); // unsubscribe timer
  this.startTimer(); // re subscribe timer
  this.triggered++;
  // your code
}

codesandbox ui example

我希望这对您有所帮助,如果您构建另一个解决方案,请告诉我。

祝你好运,

Dev.klodian

【讨论】:

    【解决方案2】:

    使用定时器的订阅属性,

    const source = timer(0, 300000);
    source.subscribe((_) => this.reload());
    

    【讨论】:

      【解决方案3】:

      试试下面的代码。它将设置间隔方法,当订阅 refreshInterval$ 时,您可以调用 reload 方法或您想要重复的任何操作。

      const refreshInterval$: Observable<any> = timer(0, 300000)
        .pipe(
          // Boolean to kill the request if the user closes the component 
          takeWhile(() => this.killTrigger));
      refreshInterval$.subscribe(() => {
          // Your code here 
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 2020-06-19
        • 2019-11-15
        • 1970-01-01
        • 2020-09-03
        • 2020-10-06
        相关资源
        最近更新 更多