从数组创建可观察

时间:2019-05-01 04:44:02

标签: javascript angular firebase

我想根据事件的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()
 }

1 个答案:

答案 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();
}
  1. 使用switchMap跳转到另一个可观察的
  2. 使用eventKeys.map遍历所有事件键并查询每个事件键的值更改。
  3. 使用CombineLatest()将所有事件可观察值分组为一个可观察值。

这一切的简化版本可以是:

//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);
  })
);