如何使用内部可观察对象映射可观察对象?

时间:2021-05-29 23:25:16

标签: angular rxjs

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

以下是我获取项目详细信息的方法。我想将接收到的对象映射为未包装的属性。

              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))
                      ),
                    };
                })
              )

2 个答案:

答案 0 :(得分:0)

试试这个,设置一个 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 })),
);

答案 1 :(得分:0)

这是一个 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}))
);
相关问题