我已经查看了很多有关如何解决此问题的示例,但没有一个解决方案适合我。我有一个类递归运行一个进程 20 次,并且我在可观察对象中跟踪该进程。我想使用这些值在 View 上创建进度条。
我知道 observable 正在工作,因为如果我直接在我的组件和 console.log 中订阅数字,它们就会按预期以 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 }}
最佳答案
当您递归调用 this.generateCalendar
时,只需将其包装在 setTimeout
中,如下所示:
setTimeout(() => this.generateCalendar(), 0)
将超时设置为 0 时,会将下一个计算移至执行队列的末尾,从而使 UI 有机会呈现更改。
关于angular - 我认为变量不会反射(reflect)可观察值的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905627/