我需要进行不同的API调用。
第1次接口调用返回具有userId、propertyId的对象的info列表
对于每个项目,我需要根据第一次userInfo调用返回的ID获取propertyinfo和API。
最后,它必须返回info、userInfo、popertyInfo。
我想写一次订阅方法,使这些应用程序接口调用在ts文件中。
this.service.getInfo().subscribe((data) => {console.log('should list all the information')} //应打印信息、userInfo、propertyInfo
我有以下代码:
getInfo() {
return this.http.get().pipe(
mergeMap((info) => {
})
}firstAPI:
[
{
info: 'some info 1',
userId: 1,
propertyId: 4,
},
{
info: 'some info 2',
userId: 2,
propertyId: 5,
},
{
info: 'some info 3',
userId: 3,
propertyId: 6,
},
];每隔一个接口:(从第一个接口调用的每个数组元素中获取userId )
{
userName: 'asdasd',
age: 34
}每三个api调用:(从第一个API调用的每个数组元素获取propertyId )
{
propertyName: 'adasd',
otherProps: ''
}最终的响应应该是这样的
res =
[
{
info: 'some info 1',
userId: 1,
propertyId: 4,
userName: 'asdasd',
age: 34,
propertyName: 'adasd',
otherProps: ''
},
{
info: 'some info 2',
userId: 2,
propertyId: 5,
userName: 'a',
age: 34,
propertyName: 'b',
otherProps: ''
},
...
...
]发布于 2020-07-02 23:55:56
你可以用下面的方法来做:
getInfo() {
return this.http.get().pipe(
mergeMap((info: {userId: number, propertyId: number}[]) => {
const userIdRequests = info.map(item => this.http.get(`/second-api/${item.userId}`));
const propertyIdRequests = info.map(item => this.http.get(`/third-api/${item.propertyId}`));
const userIdData$ = forkJoin(userIdRequests);
const propertyIdData$ = forkJoin(propertyIdRequests);
return forkJoin([userIdData$, propertyIdData$]).pipe(
map(([userIdList, propertyIdList]) => {
const result = [];
info.forEach((infoItem, index) => {
const resItem = {
...infoItem,
...userIdList[index],
...propertyIdList[index]
};
result.push(resItem);
});
return result;
})
)
})
)
}这里使用mergeMap返回新的observable,而不是第一个observable。
forkJoin用于三次等待所有请求结束,也用于对请求进行分组(按接口调用的类型、用户或属性)
map函数用于将(info, userIdInfo, propertyIdInfo)中的三个数组转换为预期结果。
我对你的API调用URL做了一些假设。而变量名则是来自你的域的费用。但关键的概念是show。
https://stackoverflow.com/questions/62698362
复制相似问题