以下observable创建一个事件对象数组。
eventsRef: AngularFireList<any>;
events: Observable<any>;
this.eventsRef = db.list('events');
this.events = this.eventsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
我需要从其他数据库列表中向this.events
添加其他数据。所以我需要每个事件对象包含一个访客计数和数据eventsFilters
。我不知道该怎么做。这就是我到目前为止所做的:
this.events = this.eventsRef.snapshotChanges().map(changes => {
changes.map(data => {
console.log(data.payload.key)
this.db.object(`/eventsFilters/${data.payload.key}`)
.valueChanges()
.subscribe(data => {
console.log(data) //event filters
})
})
changes.map(data => {
console.log(data.payload.key)
this.db.object(`/eventsGuests/${data.payload.key}`)
.valueChanges()
.subscribe(data => {
let guestCount = Object.keys(data).length;
console.log(guestCount)
this.guestCount = guestCount; //guest count
})
})
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
编辑--------
我使用combineLatest
得到了这么多,但我仍然不确定如何对每个事件数据进行分组。
this.eventsRef.snapshotChanges()
.switchMap(
(changes) => {
let userQueries: Observable<any>[] = [];
let lists: Array<string> = ['eventsFilters', 'eventsGuests'];
changes.map(data => {
for (let list of lists) {
userQueries.push(this.db.object(`/${list}/${data.payload.key}`).valueChanges());
}
})
userQueries.push(this.eventsRef.snapshotChanges());
return Observable.combineLatest(userQueries);
})
.subscribe((d) => {
console.log(d)
});
console.log(d)
输出如下内容:
[
{}, //object with data from eventsFilters for first event
{}, //object with data from eventsGuests for first event
{}, //object with data from eventsFilters for second event
{}, //object with data from eventsGuests for second event
...
[{},{} ...] //array with all events
]
答案 0 :(得分:0)
这是一个结合3个可观察的例子:
combinedData$ = combineLatest( entityList$, settings$, currentUser$).pipe(
map(([entityList, pageSetting, currentUser]) => {
//entityList, pageSettingand currentUser holds the last value emitted on each observables.
if (!pageSetting.ShowAllOrganisation) {
//If not showing all organisation, then we have to filter it
retVal = entityList.filter(entity=> entity.organisationId === currentUser.organisationId);
}
return retVal;
})
);
CombineLatest将返回一个新的observable。如果3个可观察者中的一个弹出一个新值,则将触发combineLatest并触发新值。有关combineLatest如何工作的更多信息,请访问official documentation