簡體   English   中英

如何使用內部可觀察對象 map 可觀察 object?

[英]How to map observable object with inner observables?

如何使用內部可觀察對象 map 可觀察 object?

以下是我如何獲取項目的詳細信息。 我想 map 收到的 object 具有未包裝的屬性。

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

試試這個,設置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 })),
);

這是聚合 RxJS 請求的示例。

由於只有 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}))
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM