【问题标题】:How to map observable object with inner observables?如何将可观察对象与内部可观察对象映射?
【发布时间】:2021-05-29 23:25:16
【问题描述】:

如何将可观察对象与内部可观察对象映射?

以下是我获取项目详细信息的方式。我想将接收到的对象映射到一个展开的属性。

              this.fetchData.getItemData().pipe(
                mergeMap((item: any) => {
                    return {
                        ...item,
                        images: item.images.map(id => this.http.get(baseUrl + link)) -->> I want to unwrap here. (it is an observable; that's why!)
                    }
                })
              )

在这里,我将作为数组的内部属性图像映射到可观察对象数组!!!

这是我尝试过的:


              this.fetchData.getItemData().pipe(
                forkJoin((item: any) => {
                    return {
                        ...item,
                        images: item.images.map(id => this.http.get(baseUrl + link)) 
                    }
                })
              )


              this.fetchData.getItemData().pipe(
                mergeMap((item: any) => {
                    return {
                      ...item,
                      images: item.images.map((id) =>
                        flatMap(() => this.http.get(baseUrl + link))
                      ),
                    };
                })
              )

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    试试这个,设置一个外部值itemResponse,然后再使用它。

    import { mergeMap, map } from 'rxjs/operators';
    ....
    let itemResponse: any;
    this.fetchData.getItemData().pipe(
      mergeMap((item: any) => {
        // assign itemResponse to item be used later
        itemResponse = item;
        // switch to all images
        return forkJoin(...item.images.map((id) => this.http.get(baseUrl + link)));
      }),
      // spread itemResponse and assign images property to images value and return the object
      map(images => ({ ...itemResponse, images })),
    );
    

    【讨论】:

      【解决方案2】:

      这是Aggregating RxJS Requests 的示例。

      由于只有 2 个级别的请求,您可以简单地嵌套:

      this.fetchData.getItemData().pipe(
        mergeMap((item: any) => forkJoin(item.images.map(id => this.http.get(baseUrl + link))).pipe(
          // At this point all previous results are in scope so format the result as required
          map(images => ({...item, images})
        )
      );
      

      如果您不喜欢嵌套,或者想要更通用的解决方案,您可以使用实用运算符 concatJoin(请注意,我参与了它的实现):

      // fetch all the data, with all results aggregated into an object
      concatJoin(
        {item: this.fetchData.getItemData()},
        {images: ({item:any}) => forkJoin(item.images.map(id => this.http.get(baseUrl + link)))}  
      ).pipe(
        // convert it into the format you want
        map(({item:any, images}) => ({...item, images}))
      );
      

      【讨论】:

        猜你喜欢
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        • 2021-11-13
        • 1970-01-01
        • 2017-06-02
        相关资源
        最近更新 更多