退出应用时控制台报错Cannot read property 'uid' of null的问题排查
Let's break down exactly what's causing this error and fix it for you. The issue pops up when users log out because Firebase's onAuthStateChanged callback fires with user = null (since there's no authenticated user anymore). Your current code doesn't handle this null state, so when you try to access this.currentUser.uid, you're trying to read a property from a null value—hence the error.
Here's how to resolve this step by step:
Handle the logout (null user) case first
Add an explicit check at the start of the callback to reset your variables when there's no authenticated user. This stops any attempts to access properties on a null value.Use the callback's
userparameter directly
Theuserpassed toonAuthStateChangedis already the current authenticated user (or null), so callingfirebase.auth().currentUseragain is redundant and less reliable. Just use the parameter directly.
Modified Working Code
constructor(private firestore: AngularFirestore, private auth: AuthService) { firebase.auth().onAuthStateChanged(user => { // Handle logout scenario first if (!user) { this.currentUser = null; this.vendor = null; // Reset the vendor reference too to avoid stale data return; } // Only update if the user state actually changed if (this.currentUser !== user) { this.currentUser = user; this.vendor = firebase.firestore().doc(`/Products/${this.currentUser.uid}`); } }); }
Extra Tips for Better Angular + Firebase Integration
- Switch to AngularFireAuth
Since you're already using AngularFirestore, it’s cleaner to use the AngularFire ecosystem for authentication too. It provides observables that integrate seamlessly with Angular's lifecycle:import { AngularFireAuth } from '@angular/fire/compat/auth'; constructor(private firestore: AngularFirestore, private afAuth: AngularFireAuth) { this.afAuth.authState.subscribe(user => { if (!user) { this.currentUser = null; this.vendor = null; return; } if (this.currentUser !== user) { this.currentUser = user; this.vendor = this.firestore.doc(`/Products/${user.uid}`); // Use AngularFirestore's doc method too } }); } - Clean up subscriptions
If you use observables (like with AngularFireAuth), remember to unsubscribe when your component is destroyed to prevent memory leaks. You can store the subscription in a variable and callunsubscribe()in thengOnDestroyhook.
内容的提问来源于stack exchange,提问作者Debugger

