繁体   English   中英

嵌套 angular http 可观察调用

[英]Nested angular http observable calls

一直在这个问题上停留了一段时间。 我想要实现的是用来自 api 的 http 响应替换产品 ID。

appConfig 响应(简化)

[
  {
    ...,
    hotspot: [
      {
        ...,
        data: {
          ...,
          products: [1234, 5678]
        }
      },
      {
        ...,
        data: {
          ...,
          products: [8910, 1112]
        }
      }      
    ]
  }
]

我目前正在使用的代码(现在真的很基础)。

public readonly loadAppConfig$ = this._retailerSrv.retailer$.pipe(
    filter((retailer) => Boolean(retailer)),
    switchMap((retailer) =>
      combineLatest([
        of(retailer),
        this._roomConfigSrv.loadAppConfig$(),
        this._authSrv.getApiKey$(retailer),
      ])
    ),
    map(([retailer, appConfigs, authResponse]) => {
      return appConfigs.map((appConfig) => {
        this._authSrv.apiKey = authResponse.access_token;
        return {
          ...appConfig,
          hotspots: appConfig.hotspots.map((hotspotConfig) => {
            if (
              hotspotConfig.type === 'products' &&
              hotspotConfig.data.products
            ) {
              return {
                ...hotspotConfig,
                data: hotspotConfig.data.products.map((productId) =>
                  this._authSrv.getProductFromApi$(
                    productId,
                    retailer
                  )
                ),
              };
            }
            return {
              ...hotspotConfig,
            };
          }),
        };
      });
    }),
    tap(console.log)
  );

这基本上用 http 可观察值代替产品 ID(不是 api 响应)返回给我。

点击结果

[
  {
    ...,
    hotspot: [
      {
        ...,
        data: {
          ...,
          products: [Observable, Observable]
        }
      },
      {
        ...,
        data: {
          ...,
          products: [Observable, Observable]
        }
      }      
    ]
  }
]

我知道会有一种更简单的方法来实现这一点,但到目前为止我还没有找到任何东西(尝试过的承诺等)。 任何帮助将不胜感激,如果您有任何其他问题,请告诉我。

干杯

您的代码没有提供有关 your.json 以及您想要得到的任何线索,但想法始终相同

  1. 你打电话来获取一个数组
  2. 您创建一个包含您需要搜索的元素的数组
  3. 你制作了这个新元素的 forkJoin
  4. 您将结果添加到第一个数组

在伪代码中,用作“灵感”

loadAppConfig.pipe(
switchMap(configData=>{
    ..here we has config..
    let products=[]; //we create an array with the products
    configData.hotspot.forEach(x=>{
       products=[...products,x.data.products] //we fill the array "products" 
    })
    return forkJoin(products.map(p=>loadProduct(p)).pipe( //we create an array of observables
        map(productResult=>{
            ..here change the "config" that is store in "configData"...
            ..using "productResult"...,e.g.
            configData.hotsport.forEach(x=>{
              const product=productResult.find(x=>p.key==x.data.product
               x.data.productData=product
            })
            ...finally...
            return configData
        }
    )  
}
))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM