Skip to main content

Command Palette

Search for a command to run...

Firestore Observables to Promises

Updated
•2 min read•View as Markdown
Firestore Observables to Promises

Firestore Observables to Promises

library_books 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

const foo = await this.afs.doc(docPath).valueChanges() .pipe(take(1)).toPromise();

or

const foo = (await this.afs.doc('docPath').get() .toPromise()).data();

or

const foo = (await this.afs.doc('docPath').get() .pipe(take(1)).toPromise()).data();

or

const foo = (await this.afs.doc('docPath').snapshotChanges() .pipe(take(1)).toPromise()).payload.data();

But the shortest is:

const foo = (await this.afs.doc('docPath').ref.get()).data();

Collections

const foo = await this.afs.collection('colPath').valueChanges() .pipe((take(1))).toPromise();

or

const foo = (await this.afs.collection('colPath').snapshotChanges() .pipe(take(1)).toPromise()).map((m) => m.payload.doc.data());

or

const foo = (await this.afs.collection('colPath').get() .toPromise()).docs.map((m) => m.data());

or (overkill from last version)

const foo = (await this.afs.collection('colPath').get() .pipe(take(1)).toPromise()).docs.map((m) => m.data());

or

const foo = (await this.afs.collection('colPath').ref.get()) .docs.map((m) => m.data());

User

As you may have noticed...

const bar = await this.afa.currentUser;

... does not load correctly in a lot of cases.

So try these:

const bar = await this.afa.authState.pipe(take(1)).toPromise();

or (authstatechanged is most accurate)

const bar = await new Observable( (observer: any) => { this.afa.onAuthStateChanged(observer) } ).pipe(take(1)).toPromise();

or

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)

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


More from this blog

Code.Build

331 posts