【问题标题】:updating a list of objects within an observable using RxJS 6 and Angular 6使用 RxJS 6 和 Angular 6 更新可观察对象中的对象列表
【发布时间】:2019-08-06 00:01:57
【问题描述】:

为我提供了两个可用的 REST API,称为 Product 和 Price。

我面临的问题是按产品名称搜索时。用户将提供一个“查询”,产品 API 将返回与该名称匹配的所有产品。然后我需要获取此列表,循环遍历每个项目以获取 sku,然后调用价格 API 以获取价格信息。

我对产品和价格的方法是:

getProductListByQuery(query: string): Observable<Product[]> {
   return this.http.get<Product[]>(this.productEndpoint + '/' + query);
}

getPriceBySku( sku: string): Observable<Price> {
   return this.http.get<Price>(this.priceEndpoint + '/' + sku);
}

产品对象如下所示:

import { Price } from './inventory';

export class Product {
  sku: string;
  name: string;
  status: string;
  price: Price;  
}

我想遍历所有产品并更新价格

我已经尝试过使用 forkJoin、mergeMap、switchMap、concatMap 以及我能找到的任何我读过的东西......但我认为归结为我只是不明白我在尝试什么去做...这可以解释为什么我不明白结果。

我的方法看起来像:

getProductandPriceByQuery(query: string): Observable<Product[]> {
   return this.productService.getProductListByQuery( query ).pipe(
           //  I want to loop through each Product and add Price.
           //  I am just stumped.
}

【问题讨论】:

  • 你是如何获得 sku 的,我没有看到你正在使用产品 ID 进行查询

标签: angular rxjs observable


【解决方案1】:

这可能是一种方法:

  getProductandPriceByQuery(query: string): Observable<Product[]> {

    return this.productService.getProductListByQuery( query ).pipe(

      switchMap(products => {
        const productWithPriceObservables = products.map(product => { 
          return this.productService.getPriceBySku( product.sku )
            .pipe(
              map(price => Object.assign(product, {price: price}))
            );
        });
        return combineLatest(productWithPriceObservables);
      })

    )

 }
  1. 首先我得到产品。
  2. 然后我使用“switchMap”表示我将跳转到一个新的 observable。 “mergeMap”在这里也是一个有效的选项,具体取决于您的用例。
  3. 对于我查询价格的每个产品,我将价格合并到产品中:

    map(price => Object.assign(product, {price: price}))
    
  4. 我使用 combineLatest 等待返回所有价格,然后再返回所有内容。

【讨论】:

  • 非常感谢。我需要做一些小的调整,但那是因为我没有向您提供完整的代码。我现在可以在一个对象中看到带有价格的产品,这正是我所需要的。现在我将研究这段代码以增加我对该主题的了解。
猜你喜欢
  • 1970-01-01
  • 2015-12-17
  • 2018-10-25
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2016-06-18
  • 1970-01-01
相关资源
最近更新 更多