问题
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