1
votes

I have two nodes in my database - one which is allUsers and one which is usersChildren.

For example:

allUsers: { user1: {...}, user2: {...}}
usersChildren: { user1: {...} }

In this case user1 has children data and user2 does not.

I want to retrieve a list of all user objects, and inside each user's object I wish to add the children data from the usersChildren node(if there is one).

However, I am not really familiar with how I can do that. I have tried the following but this results in obtaining only the children information and not a combined object with both the children information and the user meta data.

this.af.getObservable(`allUsers`).pipe(map(allUsers =>
    allUsers.map(user => this.af.getObservable(`usersChildren/${user.id}`)))
   .subscribe(allUsersData => this.userList = allUsersData);

What is the best way to achieve what I desire?

2

2 Answers

0
votes

Try this

this.af.getObservable(`allUsers`)
  .pipe(
    mergeMap(users => forkJoin(
      users.map(user => this.af.getObservable(`usersChildren/${user.id}`))
    ))
  );

You make an HTTP call to get all the users, then you use forkJoin to make 1 call per user. The call is made thank to Array.map, which transforms your user into an HTTP call.

Now you can subscribe to it like this

this.myService.getAllUsers().subscribe(users => { console.log(users); });
0
votes

I would use concat operator in your case.

Concat will combine two observables into a combined sequence, but the second observable will not start emitting until the first one has completed.

Example:

let first = Observable.timer(10,500).map(r => {
  return {source:1,value:r};
}).take(4);
let second = Observable.timer(10,500).map(r => {
  return {source:2,value:r};
}).take(4);
first.concat(second).subscribe(res => this.concatStream.push(res));