使用RxJS 6和Angular 6更新observable中的对象列表


没身份别烦我
2025-03-12 02:08:25 (24天前)
  1. 我提供了两个名为Product and PriceREST API

我面临的问题是按产品名称搜索时。用户将提供“查询”,产品API将返回所有…

2 条回复
  1. 0# 绵绵 | 2019-08-31 10-32



    这可能是一种方法:




    1. getProductandPriceByQuery(query: string): Observable {

    2. return this.productService.getProductListByQuery( query ).pipe(
    3.   switchMap(products => {
    4.     const productWithPriceObservables = products.map(product => { 
    5.       return this.productService.getPriceBySku( product.sku )
    6.         .pipe(
    7.           map(price => Object.assign(product, {price: price}))
    8.         );
    9.     });
    10.     return combineLatest(productWithPriceObservables);
    11.   })
    12. )
    13. }

    14. </code>



    1. 首先,我得到了产品。


    2. 然后我使用“switchMap”来表示我将跳转到一个新的observable。 “mergeMap”也是一个有效的选项,具体取决于您的用例。



    3. 对于每个产品,我查询价格,并将价格合并到产品中:




      1. map(price => Object.assign(product, {price: price}))

      2.     </code>
      3.   </pre>
      4. </LI>
      5. <LI>
      6.   <P>
      7.     我使用combineLatest在返回所有内容之前等待返回所有价格。
      8.   </p>
      9. </LI>
      10. </醇>

登录 后才能参与评论