【问题标题】:Transform api result to collect additional data from additional api requests转换 api 结果以从额外的 api 请求中收集额外的数据
【发布时间】: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 方式”。

【问题讨论】:

    标签: angular rxjs


    【解决方案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()
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 2019-08-02
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多