簡體   English   中英

使用 map 組合兩個 rxjs 可觀察對象的數據

[英]Combing data of two rxjs observables using map

我有兩個服務調用兩個獨立的外部 API(productDataService、productPrice),它們返回 observables。 然后我有一個名為 productService 的第三個服務,它最終需要將一個 observable 返回給我的 controller,這是從兩個外部服務調用函數的結果。 正如您將在下面看到的,我從一項服務(外部可觀察)獲取產品列表,然后需要依次調用另一項服務 function(內部可觀察)以獲取該產品的價格。

// Both services functions are using HttpService and returning observables.
getProductInfo() {
    return this.productDataService.getProducts()
        .pipe(map((prod: any) => this.productPriceService.getProductPriceById(prod.id)
            .pipe(map(price => {
                (
                    {
                        id: prod.created,
                        name: prod.amount,
                        price
                    }
                )
            }))))
}

以下是服務功能供參考:

// getProducts (returns an observable of an array of type product)
        return this.httpService.get(url, config).pipe(map(res => res.data.list.map(item => {
            return {
                id: item.id,
                name: item.name
            }
        })));

// getProductPriceById (returns an Observable of type number)
return this.httpService.get(url, config).pipe(map(res => res.data.price));

嘗試在外部.pipe調用中使用switchMap運算符而不是map運算符。

getProductInfo() {
  return this.productDataService.getProducts()
    .pipe(switchMap((prod: any) => this.productPriceService.getProductPriceById(prod.id)
      .pipe(map(price => {
        ({
          id: prod.created,
          name: prod.amount,
          price
        })
      }))))
}

暫無
暫無

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

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