[英]Concat multilevel API calls in Angular using rxjs
我是 rxjs 的新手,我正在使用黑客新 api 调用三个 api 调用。 我想将最后一个 api 调用的响应连接到第二个 api 调用。
我想实现这样的目标。
[
{
"by": "john"
"title": "Sample title"
"time":1657786985
"karma": 123456 // this is from the third api call that i want to merge
},
{
"by": "jane"
"title": "Sample title 2"
"time":1657786333
"karma": 123456 // this is from the third api call that i want to merge
}
]
到目前为止,这是我的代码
this.service.fetchStories().pipe( // get list of id array
switchMap(idArray => forkJoin(
idArray.map(id => this.service.fetchStoryItems(id).pipe( // first api call
concatMap(itm => this.service.fetchUserById(itm.by)) // second api call i want to merge { karma } to the first api call
)))
),
take(1)
).subscribe(data => console.log(data));
但结果是我只得到了最后一个 api 调用的响应。 有人可以帮助我。 我正在尝试学习 rxjs。
您需要做的就是再次管道第三次调用并合并结果。
this.service.fetchStories().pipe( // get list of id array
switchMap(idArray => forkJoin(
idArray.map(id => this.service.fetchStoryItems(id).pipe( // first api call
concatMap(itm => this.service.fetchUserById(itm.by).pipe(map(({karma}) => ({ ...itm, karma }))))
)))
),
take(1)
).subscribe(data => console.log(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.