【问题标题】:RXJS - return observable value when doing a mapRXJS - 做地图时返回可观察值
【发布时间】:2021-02-28 03:46:13
【问题描述】:

我有一个 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?
  };
});

【问题讨论】:

    标签: javascript rxjs rxjs-observables


    【解决方案1】:

    您可以将其包装在 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&lt;InputValue&gt; 数组

    inputIds.map((attributeName: string) => this.inputService.getInputFieldObject(attributeName))
    

    2. 我们将每个对this.inputService.getInputFieldObject() 的调用通过管道传输到映射以返回attributeName 和inputValue。所以,相反,我们现在返回一个数组 Observables&lt;{ name: attributeName, value: inputValue }&gt;

    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() 上的错误回调,而不是成功回调。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多