【问题标题】:Angular 6 run code every 5 seconds but it emits for 1st timeAngular 6 每 5 秒运行一次代码,但它第一次发出
【发布时间】:2019-06-14 02:54:06
【问题描述】:

我想在我的代码进入我的组件后立即运行它并每 5 秒重复一次逻辑

这是我的代码,我使用了rxjs的区间

ngOnInit() {
  const ticker = interval(5000);
  ticker.subscribe(() => {
    this.calculateTime();
  });
}

但这里的问题是代码运行

1st time at 5s 
2nd time at 10s

但我希望它运行为

1st time at 0s 
2nd time at 5s
3rs time at 10s

这就是我的做法:

ngOnInit() {
  const ticker = interval(5000);
  this.calculateTime();
  ticker.subscribe(() => {
    this.calculateTime();
  });
}

如果你注意到我在股票代码之前和第二个内部股票代码之前两次打电话给this.calculateTime();

使用 interval 是否有更好的解决方案?如果不是可以替代interval

【问题讨论】:

标签: javascript angular typescript rxjs intervals


【解决方案1】:

尝试以下方法:

import { startWith } from 'rxjs/operators';
// ....
const ticker = interval(5000).pipe(
     startWith(0)
);

【讨论】:

  • [ts] 类型“Observable”上不存在属性“startWith”。 [2339]
  • 你使用的是哪个版本的 RxJS?
  • 我使用的是 Rxjs 6.3.3
  • 查看更新的答案,但接受的答案是更好的方法。
  • 还是一样的问题
【解决方案2】:

您可以使用timer。它与interval 的作用相同,但添加了您需要的功能:控制第一次发射。

ngOnInit() {
  const ticker = timer(0, 5000);
  ticker.subscribe(() => {
    this.calculateTime();
  });
}

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 2018-12-19
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2011-03-20
    • 2014-08-21
    相关资源
    最近更新 更多