angular - Angular observable 没有得到初始值
问题描述
我的屏幕上有三个组件,其中一个是从数据库中提取的列表。两人等待列表加载。用户可以在其他两个组件之间切换,列表不需要重新加载。
我正在使用一项服务来告诉这两个组件列表已完成加载。
当列表完成时,将显示当前查看的组件。但是,如果用户在列表加载后切换视图,则新视图仍在等待可观察对象触发。
editor.service.ts:
...
private setBusReady = new Subject<boolean>();
...
getBusReady = this.setBusReady.asObservable();
...
busReady(values: boolean = false) {
this.setBusReady.next(values);
}
list.component.ts(加载后将 busReady 设置为 true)
...
this.editorService.busReady(true);
...
viewer.component.ts(订阅并等待列表)
...
ngOnInit() {
...
this.editorService.getBusReady
.pipe(
takeUntil(this.unsubscribe)
)
.subscribe(res => {
if (res) {
this.loading = !res;
}
});
...
}
...
带有订阅的视图在加载时没有问题,但在切换时会出现问题。我想我需要切换到一个热门的 observable,但我不确定。我尝试使用 a 来执行此操作,ConnectableObservable
但这会导致其他问题。
解决方案
我认为您应该使用BehaviourSubject,因为Subject 在您订阅时不保存当前值,它只会在 .next (仅加载数据的那一刻)触发,另一方面BehaviourSubject可以保存一个先前的值和所有即将到来的
推荐阅读
- c - 函数 yes_or_no 应该返回 1 或 0,并根据它结束或循环程序,但它永远循环
- node.js - 手动刷新或写入时,React 路由器 URL 不起作用。并获取 html 数据而不是 JSON 数据
- python - 我怎样才能用python杀死一个线程
- c# - C# 客户端 SocketIoClientDotNet.Client 不起作用(节点服务器)
- c# - 从串行数据数组中解码和重新格式化值
- python - Heroku 连接到随机 postgresql 服务器而不是 MongoDB
- firebase - 使用 AppEngine 和 Firebase 身份验证电子邮件模板的自定义域
- arrays - 在 Python3 中为多维 numpy 图像添加额外维度
- xml - talend - 处理多个 XML 文件 - 不同语言的相同内容
- php - 验证规则唯一性至少需要 1 个参数。unique/require 参数问题