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。这将为inputIds中的每个attributeName调用inputService.getInputFieldObject()。返回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。然后我们用forkJoin包装所有这些,然后订阅它。forkJoin可以接收一个observable数组并等待所有完成。通过这样做,我们在处理结果之前等待所有可观察对象返回它们(最终)发出的值。因此,你在subscribe()中收到的值将是{ name: string, value: InputValue }的数组:

forkJoin(
....
).subscribe((result: { name: string, value: InputValue }[]) => {
// do what you need to do with the result
})

重要提示:

如果对inputService.getInputFieldObject()的任何调用失败,将触发subcribe()上的错误回调,而不是成功回调。

最新更新