angular - 我认为变量不会反射(reflect)可观察值的值

标签 angular typescript asynchronous angularjs-directive observable

我已经查看了很多有关如何解决此问题的示例,但没有一个解决方案适合我。我有一个类递归运行一个进程 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 有机会呈现更改。

<强> Here is a StackBlitz demo

关于angular - 我认为变量不会反射(reflect)可观察值的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905627/

相关文章:

javascript - Angular 2+ 检查内容是否与父容器重叠

html - 滚动到达特定点时进行 Angular 检测

javascript - 可以使用 ScriptSharp/TypeScript 编写 WinRT UI JavaScript

javascript - 加载两个组件时Angular 9调用函数

javascript - typescript /Angular : Filter array of objects

json - 语法错误 : Unexpected token C in JSON at position 0

javascript - 如何在 React 中使网站主题在刷新时保持不变?

typescript 无法破坏联合类型

java - 空指针异常(未解决)和无法将 WSResponse 映射到 play 2.4 中的结果(这部分已解决。我猜)

java - Java 中的多线程,跟踪成功和失败的任务