rxjs - 等待 Observable 在 Array.Map 内部完成
问题描述
我有一个对象数组,其中一个键包含客户 ID。
const customerArray = [{ customerId: 123, ...}, { customerId: 456, ...}];
我想遍历此数组并进行 api 调用,以从单独的端点获取有关此客户的更多详细信息。
const mapped = customerArray
.map(customer => ({
customerId: customer.customerId,
rating: this.productService(customer.customerId)
.pipe(map(rating => rating))}));
我的期望是,我将拥有一个包含具有以下形状的对象的数组:
{
customerId: number,
rating: number
}
相反,我最终得到:
{
customerId: number,
rating: Observable
}
我的productService
调用返回 observable 并成功在应用程序的其他地方使用。在映射到数组中的下一个项目之前,我需要map
等待对评级键的调用完成。
解决方案
如果我理解正确,您必须遍历数组,为数组的每个元素向端点发出 http 请求,并用端点返回的数据填充数组的每个元素。所以,如果是这种情况,你可以试试mergeMap
这样
const myObs = from(customerArray).pipe(
mergeMap(customer => {
return this.productService(customer.customerId).pipe(
map(rating => ({customerId: customer.customerId, rating}))
)
})
)
如果你订阅myObs
你应该得到你正在寻找的形状的对象流,即
{
customerId: number,
rating: number
}
mergeMap
,以前称为flatMap
,允许您扁平化 Observable 流。换句话说,如果您遍历一个数组以生成一个 Observables 数组,这应该是您的情况,mergeMap
允许您提取生成的 Observables 中的值。