angular - 动态改变间隔 Angular 的频率
问题描述
在构造函数中,我有一个函数:
const inter= interval(1000);
inter.subscribe(val => {this.function()});
默认情况下,我的函数每 1 秒调用一次。我有一个输入字段,用户可以在其中传递新的时间间隔。如何将调用this.function()
频率更改为从输入中获得的频率?
解决方案
使用Subject
s:
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!');
}
推荐阅读
- c# - Microsoft.AspNetCore.Mvc.Razor.RazorPage
.Model.get 返回 null - 如何解决这个问题? - html - 如何使图像显示在文本的右侧?
- mongodb - 将数据从 Redshift(或 csv 文件)传输到 MongoDB 到现有集合
- flutter - 访问 DialogFlowAPI 时出现 Flutter 聊天机器人 HandshakeException
- openmdao - MDO 测试套件:使用 OpenMDAO 的 Golinski 减速器问题
- android - 尽管在 build.gradle 中设置了源目录,Jacoco 还是找不到源文件
- php - 在哪里使用 switch_to_locale() WordPress 功能?
- javascript - 我有一个循环创建几个 Ajax 调用。如何将 .then() 响应与我在循环中创建的正确元素联系起来?
- visual-studio-code - 所有没有扩展名的文件的shellcheck vscode“shellcheck.ignorePatterns”
- list - 我应该如何处理错误:“列表索引必须是整数..”