我想在代码进入组件后立即运行并每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
答案 0 :(得分:1)
您可以使用timer
。它的作用与interval
相同,但增加了所需的功能:控制第一个发射。
ngOnInit() {
const ticker = timer(0, 5000);
ticker.subscribe(() => {
this.calculateTime();
});
}
答案 1 :(得分:0)
尝试以下操作:
import { startWith } from 'rxjs/operators';
// ....
const ticker = interval(5000).pipe(
startWith(0)
);