我有两个API请求。
getActiveID
,这将为我获取每个团队的activeID。每个团队都有自己的ID
getActiveIDdetail
基于activeID,我将使用此功能来获取详细信息。
应用组件
// Team date with it's unique ID
public teamData = [
{ title: 'Team1', id: '22407' },
{ title: 'Team2', id: '21756' },
{ title: 'Team3', id: '18278' },
{ title: 'Team4', id: '21316' },
{ title: 'Team5', id: '8523' },
{ title: 'Team6', id: '21280' },
{ title: 'Team7', id: '18573' },
{ title: 'Team8', id: '22696' },
{ title: 'Team9', id: '21783' },
{ title: 'Team', id: '20632' }
];
this.teamData.map(x => {
if (x.id) {
this.getActiveID(x.id);
}
});
getActiveID(id) {
this.service.getActiveID(id).subscribe(response => {
const activeID = response.sprints.slice(-1)[0].id;
this.getActiveIDdetail(activeID);
});
}
服务TS
getActiveID(id: string) {
return this.http.get<any>('/get-active-id/' + id);
}
getActiveIDdetail() {
return this.http.get<any>('/get-active-id-detail/' + id);
}
问题是,我有10个团队,所以我要发出10个http请求,而所有这些请求都不是顺序的。
如何将所有响应合并为单个响应,还请建议我提出HTTP请求的更好方法?
答案 0 :(得分:0)
您可以尝试一下吗? 我没有测试代码,但是我认为它可以工作。
应用组件
// Team date with it's unique ID
public teamData = [
{ title: 'Team1', id: '22407' },
{ title: 'Team2', id: '21756' },
{ title: 'Team3', id: '18278' },
{ title: 'Team4', id: '21316' },
{ title: 'Team5', id: '8523' },
{ title: 'Team6', id: '21280' },
{ title: 'Team7', id: '18573' },
{ title: 'Team8', id: '22696' },
{ title: 'Team9', id: '21783' },
{ title: 'Team', id: '20632' }
];
ngOnInit() {
this.service.loadDetail(teamData).subscribe(console.log);
}
服务
loadDetail(teamData) {
return Observable
.from(teamData)
.map(teamMember => teamMember.id)
.mergeMap(this.getActiveID.bind(this))
.mergeMap(this.getActiveIDdetail.bind(this))
.combineAll();
}
getActiveID(id: string) {
return this.http.get<any>('/get-active-id/' + id)
.map(response => response.sprints.slice(-1)[0].id);
}
getActiveIDdetail(id: string) {
return this.http.get<any>('/get-active-id-detail/' + id);
}