【发布时间】:2019-12-20 00:54:49
【问题描述】:
我的 Angular 应用中有一个自定义的 BehaviourSubject,它在我的模板中用作 Observable。
当我在主题上调用 next 时,我希望模板中的主题得到解决。我使用async 管道来监听这个主题的异步变化。
我在 Stackblitz 中创建了一个示例来显示我遇到的问题:https://stackblitz.com/edit/angular-kmou5e
在app.component.ts 中,我创建了一个示例异步方法,它在超时后将值设置为this.data。只要设置了this.data,hello.component.ts 就会被初始化并呈现。我在HelloComponent 中收听OnChanges 并在HelloComponent 中的自定义主题上调用next()。
正如您在HelloComponent 的模板中看到的,我希望观察到的主题customSubject$ 在通过next() 获得值后立即呈现为<h1>。
您可以看到,customSubject$ 的订阅被调用,如日志所示。只有模板不会呈现这个 Observable/Subject。
使用自定义Subject 时如何让模板呈现?我需要使用不同的管道吗?
仅供参考:我还尝试使用 combineLatest 将 Subject 的值分配给新的 Observable,但效果不佳。
【问题讨论】:
-
将
new Subject()更改为new ReplaySubject(1)或new BehaviorSubject()。 learnrxjs.io/subjects/behaviorsubject.html
标签: angular rxjs observable behaviorsubject