首页 > 解决方案 > 动态改变间隔 Angular 的频率

问题描述

在构造函数中,我有一个函数:

const inter= interval(1000);
inter.subscribe(val => {this.function()});

默认情况下,我的函数每 1 秒调用一次。我有一个输入字段,用户可以在其中传递新的时间间隔。如何将调用this.function()频率更改为从输入中获得的频率?

标签: angularrxjs

解决方案


使用Subjects:


private intervalSubject = new BehaviorSubject<number>(1000); // default 1000ms interval

private interval$ = this.intervalSubject.pipe(
  switchMap(duration => interval(duration))
);

ngOnInit() {
  this.interval$.subscribe(() => this.func());
}

handleInputChanged(newInputNumber: number) {
  this.intervalSubject.next(newInputNumber); // make sure the input is of type number, not string
}

func() {
  console.log('called!');
}


推荐阅读