首页 > 解决方案 > 使用 RXJS 修改 http 响应

问题描述

我有一个返回此示例有效负载的 API -

    {
      "uid": "string",
      "queue": {
        "size": 0,
        "averageWaitTime": 0,
        "inChair": "string",
        "status": "OPEN",
        "customers": [
          {
            "uid": "1b3",
            "haircut": "SHAPE_UP",
            "hasBeard": true,
            "useScissors": true
          },
          {
            "uid": "1b2",
            "haircut": "SHAPE_UP",
            "hasBeard": true,
            "useScissors": true
          }
        ]
      }
    }

在将响应返回给调用函数之前,我需要做的是遍历客户 [] 并使用数组的每个对象中的“uid”值发出进一步的 HTTP 请求,以获得需要附加到其各自的额外数据目的。所以它看起来像这样 -

{
      "uid": "string",
      "queue": {
        "size": 0,
        "averageWaitTime": 0,
        "inChair": "string",
        "status": "OPEN",
        "customers": [
          {
            "uid": "1b3",
            "haircut": "SHAPE_UP",
            "hasBeard": true,
            "useScissors": true,
            "extra": {
                "name": "Fred",
                "telephone": "000"
            }
          },
          {
            "uid": "1b2",
            "haircut": "SHAPE_UP",
            "hasBeard": true,
            "useScissors": true,
            "extra": {
                "name": "Fred",
                "telephone": "000"
            }
          }
        ]
      }
    }

这是我迄今为止尝试过的 -

barberQueue(): Observable<BarberConfigurations> {
        return this.http.get<BarberConfigurations>( `${environment.apiEndpoint}/barber/profile` )
        .pipe(
            mergeMap( ( response: any ) => {
                return forkJoin(
                    response.queue.customers.map( customer => {
                        return this.customerService.get( customer.uid ).pipe(
                            map( resp => {
                                return {
                                    ...customer,
                                    extra: resp
                                };
                            } )
                        );
                    } )
                );
            } ),
        );
    }

这仅返回客户对象的 []。我需要的仍然是以正确的结构返回原始有效负载的其余部分。我不认为我对一些运营商很了解。

有人可以帮助我了解我哪里出错了吗?

标签: angularrxjsobservable

解决方案


您只需要在以下帮助下为每个客户返回一个新的 observablemergeMap

    return this.http.get<BarberConfigurations>( `${environment.apiEndpoint}/barber/profile` )
    .pipe(mergeMap(customer => this.customerService.get( customer.uid )
    .pipe(map( resp => {
                            return {
                                ...customer,
                                queue: {
                                  customers: customer.queue.customers.map(c => ({...c, extra: resp}))
                                }
                                
                            };
                        }), take(1)  ) ));

推荐阅读