Angular2中带有rxjs映射的嵌套http请求
我是Rxjs的新手(一般来说是Angular2),我很难理解Rxjs的精妙之处 我想对GitLab API进行两个REST调用:Angular2中带有rxjs映射的嵌套http请求,angular,gitlab,rxjs,angular2-observables,Angular,Gitlab,Rxjs,Angular2 Observables,我是Rxjs的新手(一般来说是Angular2),我很难理解Rxjs的精妙之处 我想对GitLab API进行两个REST调用: 接收某个用户的所有组(通过gitlab.com/api/v4/groups)。这将返回一个JSON,如下所示: [ { "id": 1511397, "name": "some name", "parent_id": 1505403, ... }, { "id": 1511403, "name": "some other nam
[
{
"id": 1511397,
"name": "group name",
"parent_id": 1505403,
"projects": [
{
"id": 3099499,
"description": "project 1"
},
{
"id": 3099489,
"description": "Project 2"
}
]
},
{
"id": 1194997,
"name": "a second group name",
"parent_id": 152393,
"projects": [
{
"id": 9423423,
"description": "project 3"
},
{
"id": 2394238,
"description": "Project 4"
}
]
}
]
如何做到这一点?我已经尝试过switchMap、concatMap和MergeMap,但我从来都无法让它工作……类似的东西。您需要将static Observable.of替换为$http observables
Rx.Observable.of([{userId:1}, {userId:2}])
.switchMap(ids => Rx.Observable.of(...ids))
.mergeMap(userId => {
return Rx.Observable.of([
{userId:userId, name:'project1'},
{userId:userId, name:'project2'}
]);
})
.subscribe(x=>console.log(x));
你可以这样做
getGroups() {
return this.http.get('gitlab.com/api/v4/groups')
.map(res => res.json()) // convert to object[]
.map(res => res.map(g => g.id)) // get all id
.mergeMap(gid => {
let gs = [];
gid.forEach(id => {
let req = this.http.get(`gitlab.com/api/v4/groups/${id}`);
gs.push(req);
});
return Observable.forkJoin(gs);
})
.map(res => { // we have array of Response Object
return res.map(x => x.json()); // Array.map not Observable map operator.
});
}
getGroups().subscribe(res => console.log(res))
getGroups() {
return this.http.get('gitlab.com/api/v4/groups')
.map(res => res.json()) // convert to object[]
.map(res => res.map(g => g.id)) // get all id
.mergeMap(gid => {
let gs = [];
gid.forEach(id => {
let req = this.http.get(`gitlab.com/api/v4/groups/${id}`);
gs.push(req);
});
return Observable.forkJoin(gs);
})
.map(res => { // we have array of Response Object
return res.map(x => x.json()); // Array.map not Observable map operator.
});
}
getGroups().subscribe(res => console.log(res))