Skip to content Skip to sidebar Skip to footer

Angular 4 MergeMap Issue

i am working with angularfire and i need to 'JOIN' two nodes on the key. this is my method: mergetest(userkey){ return this.db.list(`userOwnHangouts/${userkey}`) .mergeMap((han

Solution 1:

This should work in general case:

return this.db.list(`userOwnHangouts/${userkey}`)
   // flattening the array returned by `list()`
  .mergeMap((o) => {
    return o;
  })
  .mergeMap((o) => {
    return this.db.list(`hangoutInterestedUsers/${o['$key']}`).map((users) => {
       return {...o, users: users};
    });
  })
  .reduce((acc, v) => {
    acc.push(v);
    return acc;
  }, [])
  .subscribe(x => console.log('subscribe: ', x))
 }

Edit:

But because both this.db.list never completes we can't use reduce here. Also forkJoin won't work for the same reason. So the way to go is combineLatest:

this.db.list(`userOwnHangouts/${userkey}`)
    .switchMap((list: any[]) => Rx.Observable.combineLatest(
        list.map((item: any) => this.db.list(`hangoutInterestedUsers/${item['$key']}`)),
        (...results: any[][]) => {
            list.forEach((item: any, index: number) => {
                item["users"] = results[index];
            });
            return list;
        }
    ))
    .subscribe(x => console.log('subscribe: ', x))

Post a Comment for "Angular 4 MergeMap Issue"