我目前在我的服务中有一个从Firebase(Firestore)检索集合并将其作为可观察对象返回的方法。
getInstallers(): Observable<any[]> {
const installersCollection = this.afs.collection<Installer>('installers');
return installersCollection.snapshotChanges().map(installers => {
return installers.map(i => {
const data = i.payload.doc.data() as Installer;
const id = i.payload.doc.id;
return { id, ...data };
});
});
}
我有另一种方法,利用google places api并在place_id传递给它时返回一个可观察的地方。我不会包含所有内容,因为它只是知道它会返回一个可观察到的Google地方对象。
getPlaceDetails(placeId): Observable<any>
我试图做的就是这样......
getInstallers(): Observable<any[]> {
const installersCollection = this.afs.collection<Installer>('installers');
return installersCollection.snapshotChanges().map(installers => {
return installers.map(i => {
const data = i.payload.doc.data() as Installer;
const id = i.payload.doc.id;
this.getPlaceDetails(data.placeId).subscribe(place => {
return { id, ...data, ...place }
});
});
});
}
然而,这会导致该方法返回void。我试图想出一种方法将我从getPlaceDetails observable收到的数据添加到来自我的firebase集合的数据中。谢谢!
答案 0 :(得分:1)
使用swtchMap
getInstallers() : Observable<any[]> {
const installersCollection = this.afs.collection<Installer> ('installers');
return installersCollection.snapshotChanges().switchMap(installers => {
let arrayOfObservables = installers.map(i => {
const data = i.payload.doc.data() as Installer;
const id = i.payload.doc.id;
return this.getPlaceDetails(data.placeId).map(place => {
return { id, ...data, ...place }
});
});
return Observable.forkJoin(arrayOfObservables);
});
}
在某些地方叫它:
this.getInstallers().subscribe(data => {
// here we have resukt
})