angular - 我视图中的变量无法反映来自可观察对象的值
我查阅了很多关于如何在 SO 上解决这个问题的示例,但没有一个解决方案对我有效。我有一个类在递归运行一个过程 20 次,并且我在一个可观察对象中跟踪这个过程。我想使用这些值在视图上创建一个进度条。
我知道这个可观察对象是有效的,因为如果我在组件中直接订阅并在控制台输出数字,它们会像预期的那样以20的增量出现。
无论我做什么,我在视图中只能看到初始值和最终值。我无法看到进度。
这里有任何建议吗?
// my scheduler class
private calendarPercent = new Subject()
private finishedCalendarMax = 20
private finishedCalendarCount = 0
// this stuff is called recursively until we hit our finishedCalendarMax
this.finishedCalendarCount++
this.calendarPercent.next(this.finishedCalendarCount / this.finishedCalendarMax)
// get my observable
getFinishedCalendarPercent() {
return this.calendarPercent
}
// in app.component.ts i create my scheduler class
public scheduler = new Scheduler()
// in app.component.html
{{ scheduler.getFinishedCalendarPercent() | async }}
答案#1
当你递归调用 this.generateCalendar 时,只需将其包装在 setTimeout 中,如下所示:
setTimeout(() => this.generateCalendar(), 0)
将超时设置为0,这会将下一个计算移到执行队列的末尾,从而给用户界面一个机会来渲染更改。
这里是一个 StackBlitz 演示
