javascript - RXJS - 做地图时返回可观察值
问题描述
我有一个数组,inputIds
其中包含一个返回名称和值对象的地图。在地图内部,我调用this.inputService.getInputFieldObject
它返回一个Observable<InputValue>
. 如何返回订阅值而不是返回订阅值数组?所以我可以将属性作为只有名称和值的数组返回。
const attributes = inputIds.map((attributeName: string) => {
// this.inputService.getInputFieldObject returns Observable<InputValue>
const inputSubscription = this.inputService.getInputFieldObject(attributeName).subscribe((val) => val.value)
return {
name: attributeName,
value: inputSubscription, // is there a getValue method to get value of subscription?
};
});
解决方案
您可以将其包装在forkJoin中并订阅它,如下所示:
forkJoin(
inputIds.map((attributeName: string) =>
this.inputService.getInputFieldObject(attributeName).pipe(
map((inputValue: InputValue) => {
return {
name: attributeName,
value: inputValue
};
})
)
).subscribe(
(result: { name: string, value: InputValue }[]) => {
// do what you need to do with the result
},
(error) => {
// add code here if you need to handle failure on any of the calls
// to this.inputService.getInputFieldObject(), or any processing thereafter.
}
);
解释代码在做什么:
1.这要求inputService.getInputFieldObject()
每个attributeName
in inputIds
。这将返回一个数组Observables<InputValue>
inputIds.map((attributeName: string) => this.inputService.getInputFieldObject(attributeName))
2.我们通过管道将每个调用传递this.inputService.getInputFieldObject()
给映射以返回attributeName 和inputValue。所以,相反,我们现在返回一个数组Observables<{ name: attributeName, value: inputValue }>
this.inputService.getInputFieldObject(attributeName).pipe(
map((inputValue: InputValue) => {
return {
name: attributeName,
value: inputValue
};
})
)
3.然后我们用 a 包裹所有这些,forkJoin
然后订阅它。forkJoin
可以接收一组 Observables 并等待它们全部完成。通过这样做,我们在处理结果之前等待所有可观察对象返回它们的(最终)发射值。因此,您在 中收到的值subscribe()
将是一个数组{ name: string, value: InputValue }
:
forkJoin(
....
).subscribe((result: { name: string, value: InputValue }[]) => {
// do what you need to do with the result
})
重要的提示:
如果任何调用inputService.getInputFieldObject()
失败,subcribe()
将触发您的错误回调,而不是成功回调。
推荐阅读
- android - 重新激活时 Firemonkey TCameraComponent 质量发生变化
- java - 如何运行启动画面,然后是介绍滑块,然后是主要活动
- javascript - 如何在 SharePoint 上处理 JavaScript 预订系统的同时请求
- node.js - 猫鼬在哪里,我无法过滤数组
- javascript - 如何按单个页面对 Firestore 数据集进行分页?
- docker - 无法使用凭证存储在 Ubuntu 18 上登录 Docker
- javascript - 字符串中变量的值不变
- sql - 在 SQL (SSMS) 中通过 LIKE 运算符传递列表
- java - java.util.logger - FileHandler 没有创建文件,所以 Logger 可以写入它
- angular - Angular 2-6 中子组件的两种方式数据绑定和更改检测