使用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";值,以获得需要附加到其相应对象的额外数据。所以它看起来像这样-

{
"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
};
} )
);
} )
);
} ),
);
}

这只是返回一个客户对象。我需要的仍然是以正确的结构返回原始有效载荷的其余部分。我想我不太了解一些接线员。

有人能帮我理解我哪里出了问题吗?

您只需要在mergeMap的帮助下为每个客户返回一个新的可观察对象

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)  ) ));

我认为你已经做到了99%。您已经用额外的数据丰富了客户,现在您只需要一个步骤就可以将丰富的数组插入到原始有效负载中。

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

你也可以分离出一些逻辑,使你的代码更加清晰

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

最新更新