Warm tip: This article is reproduced from serverfault.com, please click

angular-rxjs运算符,如何在单个对象中返回嵌套数据?

(angular - rxjs operators, how to return nested data in a single object?)

发布于 2020-11-30 10:32:13

我找不到以rxjs方式获取嵌套数据的干净方法。

有一个 Observable 到的返回所有用户,一个 Observable 到的返回给定用户ID的所有帖子。

getUsers(): Observable<User[]>

getPosts(id: string): Observable<[]>

我如何返回用户列表,包括他们的帖子?

目前,我使用2个嵌套订阅来准备数据。

nestedFetch() {
  this.service.getUsers()
  .subscribe(
    res => {
      res.forEach((user) => {
        this.service.getPosts(user.Id).subscribe(
          posts => {
            user.posts = posts;
            this.users.push(user);
          },
          err => console.log('something went wrong: ' + err)
        )
      })
    },
    err => console.log('something went wrong: ' + err)
  );
}

我宁愿使用像这样的运算符。但是我该如何返回包括他们帖子在内的用户?

nestedFetch() {
  this.service.getUsers().pipe(
    map(users => users.map(u => this.membership.getPosts(u.id))),
    mergeMap(posts => forkJoin(posts))
  ).subscribe(
    res => this.posts = posts, //returns only posts but not users
    err => console.log('something went wrong: ' + err)
  )
}
Questioner
F.H.
Viewed
11
MoxxiManagarm 2020-11-30 22:26:09

内管有助于通过用户的帖子来扩展用户。

this.service.getUsers().pipe(
  switchMap(users => {
    const postsRequests$ = this.users.map(user => this.service.getPosts(user.id).pipe(
      // example for a error catch which would lead to an empty array not breaking the forkJoin
      // catchError(err => of([])),
      map(posts => ({ ...user, posts })),
    ));

    return forkJoin(postsRequests$);
  }),
).subscribe(/* ... */);