angular - 使用 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
};
} )
);
} )
);
} ),
);
}
这仅返回客户对象的 []。我需要的仍然是以正确的结构返回原始有效负载的其余部分。我不认为我对一些运营商很了解。
有人可以帮助我了解我哪里出错了吗?
解决方案
您只需要在以下帮助下为每个客户返回一个新的 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) ) ));
推荐阅读
- rest - 如何在颤动中处理列表/实体操作?
- html - 带有overflow-x滚动和文本左、中、右对齐的响应行
- php - Wordpress:如何覆盖特定的更新通知
- node.js - 构建 webpack.dll 时找不到 Nodejs NPM 模块
- python - 从数据框中删除行并重置索引
- python - 在python中将数据框转换为嵌套的json
- swift - 创建一个 React-Native 桥接 iOS 类的实例
- cassandra - Flink Cassandra sink 导致背压
- html - Angular 检测 dom-to-image 的变化并无限次渲染
- python - 以整数为参数并返回对应月份和年份的函数