How to merge an observable that is a property of another observable

我与影子孤独终老i 提交于 2019-12-13 18:06:51

问题


I have a list of holidays each with a user id attached to them. I would like to merge the retrieved user data to each holiday record so it returns a single observable.

I created this function

getAllHolidaysAndUsers() {

  return this.af.database.list('Holiday').mergeMap(items => {
    for (let item of items) {
      item.user = this.af.database.object(`/User/${item.userIdKey}`);        
    }
    return items;

 });
}

it returns an object like this

{
  fromDate:'20/12/16',
  toDate:'21/12/16',
  user:fireBaseObservable
}

I would like an object like this

{
  fromDate:'20/12/16',
  toDate:'21/12/16',
  user:Array[1]
}

I am struggling to access the user observable in a single subscription. Currently I'm doing nested subscribes which I know is bad form.

I've managed to get a similar example working like this

getHolidayInfo() {
  return this.getHolidaysByUserId().mergeMap(hol => {

  return this.UserList.getUserByEmail().map(user => { 
    return {hol:hol.date, user:user[0]}
  });

});

But because I have to loop through items in the first example it only returns the last result, so this technique isn't working

Here's the plunker


回答1:


You could do it like this:

getAllHolidaysAndUsers() {
  return this.holiday
    .switchMap(items => Observable.from(items))
    .flatMap(item => {
        return this.af.database.object(`/User/${item.userIdKey}`)
            .map(user => {
                item.user = user;
                return item;
            });
    })
    .toArray();
}


来源:https://stackoverflow.com/questions/41548444/how-to-merge-an-observable-that-is-a-property-of-another-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!