Is there a better way to query a specific set of data in Firebase RTDB than this? All I can think of is using forEach() and pushing to a BehaviorSubject inside subscribe on each observable emitted. Let me know! I've been stuck on this for a while.
hits = new BehaviorSubject([]);
territories = ['16830', '16832', '16838'] // Zip Codes
getTerritories(territories) {
territories.forEach(key => {
this.db.object(`locations/${key}`).snapshotChanges()
.map(zip => zip.payload.val())
.subscribe(zip => {
let currentHits = this.hits.getValue();
currentHits.push(zip);
this.hits.next(currentHits);
});
});
}
this.hits.subscribe(res => console.log(res));
You can use Observable.forkJoin()
:
Observable.forkJoin(
//this returns an array of observables.
territories.map(key => this.db.object(`locations/${key}`)
.map(zip => zip.payload.val()))
)
.subscribe(res => console.log(res));
Note that Observable.forkJoin
takes in an array of observables, and fires them in parallel, wait for all of them to complete, before emitting a value.