【发布时间】:2018-10-17 03:45:25
【问题描述】:
我有一个 api 调用,它以Observable<any[]> 形式返回结果列表。最终,我想在一个列表中显示这些数据,但该列表应包含第一个请求未附带的每条记录的其他数据。
我认为这是对问题的一个非常简单明了的描述:给一个数组的 observable,我想通过调用 web 服务来转换数组中的每个项目,然后返回一个修改后的数组 observable。
getActivePosts = (): Observable<Post[]> => {
return this.get('/Post/Active')
.pipe(
map(posts => posts.map(u => ({
title: u.title,
author: u.author,
rating: 0 // <- This is the value I have to look up elsewhere
})))
);
}
所以上面会给我帖子数组,但所有rating 的值都是0。
我的想法是我需要把数组变成一个流,这样我就可以对每个元素进行操作。然后我可以使用toArray 之后将项目放回数组中。这看起来像以下,我会假设:
getActivePosts = (): Observable<Post[]> => {
return this.get('/Post/Active')
.pipe(
map(posts => posts.map(u => ({
title: u.title,
author: u.author,
rating: 0 // <- This is the value I have to look up elsewhere
}))),
switchMap(posts => from(posts)),
tap(post => console.log('Do something with this individual item...', post)),
toArray()
);
}
甚至在我弄清楚调用下一个 api 以获取评级(目前只是 tap 来显示控制台消息)的(可能)更棘手的部分之前,我已经被卡住了。这个例子永远不会超过toArray,因为内部流(由from创建)永远不会完成。当此代码运行并订阅此函数的结果(外部可观察?)时,不会发出任何内容。我可以确认进行了初始 api 调用,并且 devtools 显示响应是一个数组,正如预期的那样。
如何对数组中的每个项目做一些事情并仍然返回一个数组?如果有这样的事情,我很想解决这个“rxjs 方式”。
【问题讨论】: