Firestore Observables to Promises

Firestore Observables to Promises

3 min read

I am crazy, so I created a quick reference. Let me know if I missed one! **Note:** afa = AngularFireAuth afs = AngularFirestore but should be same premise in any framework. ## Docs ```typescript const foo = await this.afs.doc(`docPath`).valueChanges() .pipe(take(1)).toPromise(); ``` or ```typescript const foo = (await this.afs.doc('docPath').get() .toPromise()).data(); ``` or ```typescript const foo = (await this.afs.doc('docPath').get() .pipe(take(1)).toPromise()).data(); ``` or ```typescript const foo = (await this.afs.doc('docPath').snapshotChanges() .pipe(take(1)).toPromise()).payload.data(); ``` But the shortest is: ```typescript const foo = (await this.afs.doc('docPath').ref.get()).data(); ``` ## Collections ```typescript const foo = await this.afs.collection('colPath').valueChanges() .pipe((take(1))).toPromise(); ``` or ```typescript const foo = (await this.afs.collection('colPath').snapshotChanges() .pipe(take(1)).toPromise()).map((m) => m.payload.doc.data()); ``` or ```typescript const foo = (await this.afs.collection('colPath').get() .toPromise()).docs.map((m) => m.data()); ``` or (overkill from last version) ```typescript const foo = (await this.afs.collection('colPath').get() .pipe(take(1)).toPromise()).docs.map((m) => m.data()); ``` or ```typescript const foo = (await this.afs.collection('colPath').ref.get()) .docs.map((m) => m.data()); ``` ## User As you may have noticed... ```typescript const bar = await this.afa.currentUser; ``` ... does not load correctly in a lot of cases. So try these: ```typescript const bar = await this.afa.authState.pipe(take(1)).toPromise(); ``` or (authstatechanged is most accurate) ```typescript const bar = await new Observable( (observer: any) => { this.afa.onAuthStateChanged(observer) } ).pipe(take(1)).toPromise(); ``` or ```typescript const bar = await new Promise( (resolve: any, reject: any) => this.afa.onAuthStateChanged((user) => { user ? resolve(true) : resolve(false); }, (e: any) => reject(e)) ); ``` or (the shortest) ```typescript const bar = await this.afa.user.pipe(take(1)).toPromise(); ``` And anywhere you can use `take(1)` you can use `first()` if you want to emit an error. J
rxjs