我想根据事件的ID订阅事件列表。我正在使用 AngularFire2 和 Firebase 。不确定在订阅另一个对象时创建一个可观察对象是否正确。
eventsRef: AngularFireList<any>
events: Observable<any[]>
o2: Observable<any[]>
//get all event ids for a particular user
this.eventsRef = db.list(`eventsGuestsLookup/${this.id}`)
this.events = this.eventsRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => (c.payload.key))
)
)
this.events.subscribe(data => {
console.log(data) //array with all event keys
const o1 = Observable.from(data)
this.o2 = o1.flatMap(x => {
return this.getEvent(x);
})
})
getEvent(eventid: string) {
return this.db.object(`/events/${eventid}`).valueChanges()
}
答案 0 :(得分:0)
我相信这与您想做的事情有关
//get all event ids for a particular user
this.eventsRef = db.list(`eventsGuestsLookup/${this.id}`)
this.events = this.eventsRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => (c.payload.key))
)
)
this.events
.pipe(
switchMap(eventKeys => {
eventObservables = eventKeys.map(eventKey => this.getEvent(eventKey));
return combineLatest(eventObservables);
})
)
.subscribe(data => {
// Do whatever you want to do
});
getEvent(eventid: string) {
return this.db.object(`/events/${eventid}`).valueChanges();
}
这一切的简化版本可以是:
//get all event ids for a particular user
db.list(`eventsGuestsLookup/${this.id}`).snapshotChanges()
.pipe(
switchMap(changes => {
eventObservables = changes.map(c => this.db.object(`/events/${c.payload.key}`).valueChanges());
return combineLatest(eventObservables);
})
);