Angular 8 + RxJS以及结合flatMap和forkJoin的问题

问题描述 投票:0回答:1

我试图使多个http请求依赖于先前的请求,并将返回的数据组合到最终结果对象。

我有两个端点:

  1. /properties会给我类似的信息:

    { 
      "data":[ 
        { 
          "id":1,
          "name":"Property 1",
          "units":[ 
            { 
              "id":1,
              "name":"Property 1 - Unit 1",
            },
            { 
              "id":2,
              "name":"Property 1 - Unit 2",
            },
          ],
        },
        { 
          "id":2,
          "name":"Property 2",
          "units":[ 
            { 
              "id":3,
              "name":"Property 2 - Unit 3",
            }
          ]
        }
      ]
    }```
    
  2. /properties/${property.id}/units/${unit.id}/bookings会向我返回一些与先前请求有关的对象,例如:

    {
      "data": {
        "id": 1
      },
      "meta": {
        "count": 5
      }
    }
    

我想实现的是将这两个响应合并为一个单元级别。像这样:

{
  [
    ...

    { 
      "id":2,
      "name":"Property 2",
      "units":[ 
        { 
          "id":3,
          "name":"Property 2 - Unit 3",
          "bookings_meta": {
            "count":5
          }
        }
      ]
    }
  ]
}

我创建了类似的东西,并且效果很好:


    list(): Observable<any> {
      return this.http.get('/properties').pipe(
        map((results: any) => results.data),

        flatMap((properties: any[]) => {
          if (properties.length > 0) {
            return forkJoin(properties.map((property: any) => {
              return forkJoin(property.units.map((unit: any) => {
                return this.http.get(`/properties/${property.id}/units/${unit.id}/bookings`).pipe(
                  map(({ meta }) => {
                    unit.bookings_meta = meta
                    return unit;
                  })
                )
              }))
            }))
          }
          return of([]);
        })
      );
    }


    this.list().subscribe(response => {
        console.log(response)
    })

但是我认为这不是100%正确的解决方案。我感觉forkJoin太多,也许不应该在flatMap那里?

[单位之间的预订的请求应该是独立的。

有人知道如何改进上面的代码?
javascript angular angular8 rxjs6 flatmap
1个回答
0
投票
[forkJoin将在所有调用完成后返回数据并返回结果

const combined = Observable.forkJoin( this.http.get('https:// ...properties').map((res: Response) => res.json()), this.http.get('https:// ..properties/${property.id}/units/${unit.id}/bookings') .map((res: Response) => res.json()) ) combined.subscribe(latestValues => { console.log( "latestValues" , latestValues ); });

© www.soinside.com 2019 - 2024. All rights reserved.