You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Contents
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Check if Current User Is Signed-in or for Data Existence With AngularFire
written by Jeff DelaneyA common requirement in any app is to determine if the current user is logged-in. Or you might want to check if a database record exists before performing some logic. Doing this in an elegant want throughout your AngularFire2 app is not always obvious.
While we could use RxJS, I find it much easier to handle these situations with Promises because they are NOT streams, but rather simple one-off operations.
Get the Current User
Converting an Observable to a Promise requires a completed signal from the stream. The AngularFire auth state will not complete automatically, so we pipe in the first
operator to kill it after the first emitted value.
Promise-Based Solution
If prefer this approach for the elegant async/await syntax.
import { first } from 'rxjs/operators'; |
Observable-Based Solution
Here’s the equivalent with an Observable. Not quite as elegant, especially when you need to perform this logic frequently,
import { first, tap } from 'rxjs/operators'; |
Check if a Firestore Document Exists
We can use a similar helper to determine if a certain Firestore document exists.
docExists(path: string) { |
Let’s say we want to find or create a document.
async findOrCreate(path: string, data: any) { |