Angular 6 运行 代码每 5 秒一次,但它是第一次发出

Angular 6 run code every 5 seconds but it emits for 1st time

我想 运行 我的代码一旦进入我的组件并每 5 秒重复一次逻辑

下面是我的代码,我用的是rxjs的区间

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

但这里的问题是代码 运行s

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();,第二次在内部自动收报机。

Is there a better solution using interval ? If not may be an alternative to interval

尝试以下操作:

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

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

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