首页 > 解决方案 > 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?
  };
});

标签: javascriptrxjsrxjs-observables

解决方案


您可以将其包装在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()每个attributeNamein 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()将触发您的错误回调,而不是成功回调。


推荐阅读