Looking to retrieve the user data of a logged in user from Google Firebase, I have implemented two methods for this purpose. One method fetches the authState
, while the other collects more detailed information under UserInfo
.
These methods are encapsulated within a service called UserService
:
constructor(private fireStore: AngularFirestore, private fireAuth: AngularFireAuth) {
}
public async getAuthorizedUser(): Promise<UserInfo> {
console.log('Awaiting Promise');
const user: firebase.User = await this.fireAuth.authState.toPromise();
console.log('User', user);
return this.getUserInfo(user.uid);
}
private async getUserInfo(uid: string): Promise<UserInfo> {
return this.fireStore.collection('users', ref => ref.where('uid', '==', uid))
.get()
.pipe(
map((item: firebase.firestore.QuerySnapshot) => new UserInfo(item.docs[0].data(), item.docs[0].id))).toPromise();
}
The getAuthorizedUser
method is invoked from a button event handler inside a component. The button's HTML code is as follows:
<button mat-button (click)="test()">test</button>
The implementation of the test()
method is as below:
async test() {
console.log('Starting Test');
const testVariable = await this.userService.getAuthorizedUser();
console.log('Test', testVariable);
}
Futhermore, the userService
refers to the dependency injected UserService
.
Upon execution, the console displays:
Starting Test
Awaiting Promise
This seems to indicate that the asynchronous call is not completing as expected, since the logging of
Test
or
User {...}
is missing.
Edit - and partial answer:
After further research on angularfirebase.com, it was suggested that authState
should be invoked as
const user: firebase.User = await this.fireAuth.authState.pipe(first()).toPromise();
This caused some confusion, as I had previously used the code snippet below before transitioning to observables. Despite this, my initial code worked fine without any indication of an array being returned by authState
:
this.fireAuth.authState.subscribe((user: firebase.User) => {
if (user) {
this.getUserData(user.uid);
}
});
What could be causing this discrepancy, and why does my original solution still function correctly?