Adding a document to a Firestore collection using @angular/fire returns a Promise. What I want to do is add the document, but then return an Observable of the created document. Here's what I've tried so far:
colRef: AngularFirestoreCollection = this.afs.collection<Session>('sessions');
add(session: Session): Observable<Session> {
return this.colRef.add(session).then((docRef) {
return this.colRef.doc<Session>(docRef.id).valueChanges();
})
}
Of course this doesn't work, it's trying to return a Promise<Observable<Session>>
. I know why it's not working, but not how to achieve what I'm after. Any help much appreciated!
You could use the RxJS from
method with switchMap
operator. Try the following
import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
add(session: Session): Observable<Session> {
return from(this.colRef.add(session)).pipe(
switchMap((docRef) => this.colRef.doc<Session>(docRef.id).valueChanges());
);
}
from
could be used to convert a promise to an observable.