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

rxjs operators, how to return nested data in a single object?

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

I'm unable to find a clean way of fetching nested data the rxjs way.

There's an observable returning all users and an observable returning all posts given a user id.

getUsers(): Observable<User[]>

and

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

How would I return a list of users including their posts?

At the moment I prepare the data using 2 nested subscriptions.

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)
  );
}

I would rather use operators something like this. But how can i return users including their posts?

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
0
MoxxiManagarm 2020-11-30 22:26:09

An inner pipe helps to extend the user by his posts.

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(/* ... */);