我有两个api调用,一个用于获取所有类别,另一个用于获取帖子。在posts api中,我获取类别ID,我只需要调用类别并获取类别名称,然后在帖子调用中添加名称而不是ID。我知道不建议您使用嵌套的api调用,因此我使用了flatMap
,但不知道如何实现它。
类别
[
{
"id": 5,
"name": "Angular",
"slug": "angular",
"parent": 4
},
{
"id": 4,
"name": "Tutorial",
"slug": "tutorial",
"parent": 0
}
]
帖子
[
{
"id": 1,
"categories": [
5,
4
]
},
{
"id": 2,
"categories": [
5
]
}
]
code
this.blogService.getCategories()
.pipe(
flatMap((categories: BlogCategoryModel[]) => {
console.log(JSON.stringify(categories)); // I think I have to do logic here
return this.blogService.getPosts();
})
).subscribe(posts => console.log(JSON.stringify(posts)));
预期结果
[
{
"id": 1,
"categories": [
"Angular",
"Tutorial"
]
},
{
"id": 2,
"categories": [
"Angular"
]
}
]
您可以使用mergeMap
尝试这样:
var result = this.blogService.getCategories().pipe(
mergeMap(value => this.getPosts(value[0].id)))
);