您可以将其包装在 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 可以接收一组 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() 上的错误回调,而不是成功回调。