Utilizing Firebase Authentication for email and password sign up.
The login function is performing effectively, with the following call:
await setPersistence(this.auth, browserLocalPersistence);
Upon logging in, the user data is saved to firestore after creating a new user.
The issue at hand:
Within my auth.service.ts
, I am attempting to retrieve the user document based on the auth.currentUser. The currentUser from Firebase is consistently retrieved whenever required.
This is how it's done:
this.auth.onAuthStateChanged(user => {
console.log('FIRE AUTH ON AUTH STATE CHANGED RUNNING', user);
if (user) {
this.user$ = of(user).pipe(
switchMap(async user => {
try {
const res = await getDoc(doc(this.db, 'users', user.uid));
console.log(res.data());
return res.data() as FireUser;
} catch (error) {
console.error(error);
return null;
}
})
);
} else {
this.user$ = of(null);
}
});
Initially, it works well after login. However, upon a refresh (with currentUser still being retrieved correctly), the function ceases to proceed further without any errors or notifications. It simply does not enter the switchMap block.
I confirm that the currentUser value is correctly logged right at the beginning of onAuthStateChanged..
(Alternative approach used):
onAuthStateChanged(this.auth, user => {
console.error('USER IS', user);
if (user) {
this.user$ = docData(
doc(this.db, 'users', user.uid)
) as Observable<FireUser>;
} else {
this.user$ = of(null);
}
});
To display the user$ Observable data in a component like so:
TS:
user$ = this.fireAuthService.user$;
HTML:
<div *ngIf="user$ | async as user">
<pre>
{{ user | json }}
</pre>
</div>
What might be causing the problem?
Hence, my solution (based on @Werner7's answer):
private userSubject$ = new BehaviorSubject<FireUser>(null);
get user$(): Observable<FireUser> {
return this.userSubject$.asObservable();
}
onAuthStateChanged(this.auth, async user => {
console.error('USER IS', user);
if (user) {
this.userSubject$.next(
(await getDoc(doc(this.db, 'users', user.uid))).data() as FireUser
);
} else {
this.userSubject$.next(null);
}
});