Angular上带有rxjs的嵌套API请求

我是rxjs的新手,阅读了大量文章后,我感到有些困惑。 我有很多嵌套的http请求,这些请求是从API中获取数据的。 第一个请求获取我的设备的列表,每个设备包含一个传感器列表,每个传感器包含一个温度列表。 第一个API请求返回已填充传感器阵列的设备列表,但温度阵列为空。此时,我必须为每个传感器执行一个http请求以获取温度数据。

我尝试将switchmap与forkJoin结合使用,但是在可观察的订阅中,我仅获得温度数组。 如何填充每个传感器的温度数组?

APIconnector.GetDevices()
    .pipe(
      tap(devices => {console.log(devices)}),switchMap(devices => forkJoin(devices.map(device => device.Sensors))),tap(sensors => {console.log(sensors)}),switchMap(sensors => forkJoin(sensors.map(sensor => {
        const param = {
          MinutesInterval: 30,StartDate: stDate,EndDate: new Date(),SensorIds: [sensor.Id]
        };  
        return APIconnector.GetIntervalRange(param);
      })))
    ).subscribe(data => {      
      console.log(data);
    })

我需要API返回的所有数据,而不仅仅是最后一个。

-更新-

我希望这个堆叠闪电草图能为您提供帮助。

https://stackblitz.com/edit/angular-txtemn

sdn199 回答:Angular上带有rxjs的嵌套API请求

要获得示例语法的正确性而又不引起堆叠挑战,将是一个挑战,所以我要发布一个我知道有效的示例,希望您可以从那里进行推断:

  // All products
  products$ = this.http.get<Product[]>(this.productsUrl)
    .pipe(
      tap(data => console.log('Products',JSON.stringify(data))),catchError(this.handleError)
    );

  allProductsAndSuppliers$ = this.products$
    .pipe(
      switchMap(products => forkJoin(
        products.map(product =>
          forkJoin(product.supplierIds.map(supplierId => this.http.get<Supplier>(`${this.suppliersUrl}/${supplierId}`)))
            .pipe(
              map(suppliers => ({
                ...product,suppliers: suppliers
              } as Product))
            )
        ))
      )
    );

我把它分成两部分:

products$流将获取所有产品。看来您正在做类似的事情以获取所有设备。

然后,我使用products$流并获取该产品的所有供应商,定义为allProductsAndSuppliers$

在第二个流中,我首先使用switchMap对每个产品执行另一个http请求。

然后我使用forkJoin将产品集重新发射为数组。

在第一个forkJoin中,我使用products数组映射运算符“循环”遍历每个产品。对于每种产品,我使用另一个forkJoin查找所有供应商并将它们作为数组发出。

在第二个forkJoin内,我获得了产品的SupplierIds属性中定义的每个供应商。

我通过地图运算符通过管道传递结果,该运算符构建包含产品副本及其供应商列表的Product

作为参考,我的“产品”界面如下所示:

export interface Product {
  id: number;
  productName: string;
  productCode?: string;
  description?: string;
  supplierIds?: number[];
  suppliers?: Supplier[];
}

我使用从产品中检索到的SupplierId集合填充供应商阵列。

这看起来是否适合您的情况?

,

我认为您想做的是:

service.getA().pipe(
   switchMap(resultA => forkJoin(of(resultA),service.getB(resultA ))),tap(([resultA,resultB]) => console.log({resultA,resultB}))
)
本文链接:https://www.f2er.com/3157262.html

大家都在问