转换api结果以从其他api请求中收集其他数据

时间:2018-10-16 19:23:08

标签: angular rxjs

我有一个api调用,它以Observable<any[]>的形式返回结果列表。最终,我希望将这些数据显示在一个列表中,但该列表应包含每个记录的其他数据,而这些记录并没有与第一个请求一起出现。

我认为这是对问题的非常简单的简单描述:给出一个数组的可观察对象,我想通过调用Web服务来转换数组中的每个项目,然后返回一个修改后的数组可观察对象。

>
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方式”。

1 个答案:

答案 0 :(得分:1)

您的用例现在很普遍了。您可以使用以下代码-

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
       }))),
      mergeMap(post => this.getRating(post[id]) //check the id
               .pipe(
                  tap(rating => post.rating = rating;
               )
       ),
    toArray()
    );
}
相关问题