【发布时间】:2019-08-28 16:50:49
【问题描述】:
我想从 Google Firebase 获取登录用户的用户数据。
为此,我写了两种方法;一个获取authState,另一个获取包含更详细信息的UserInfo。
这是在名为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();
}
我正在从组件中实现的按钮事件处理程序中调用getAuthorizedUser 方法。
按钮的 html 元素如下所示:
<button mat-button (click)="test()">test</button>
test() 方法实现为:
async test() {
console.log('Starting Test');
const testVariable = await this.userService.getAuthorizedUser();
console.log('Test', testVariable);
}
此外,userService 是注入的依赖项UserService。
控制台显示:
开始测试
等待承诺
因此在我看来,异步调用根本没有返回,因为我希望看到日志记录
测试
或
用户{...}
或两者兼而有之。
怎么了?
编辑 - 部分答案:
如果在angularfirebase.com 上找到更多谷歌研究,则应该将 authState 称为
const user: firebase.User = await this.fireAuth.authState.pipe(first()).toPromise();
但这让我感到困惑,因为在我决定更改为可观察对象而不是普通变量之前,我使用了下面的代码。代码有效,但是我没有看到authState返回的任何数组的迹象
this.fireAuth.authState.subscribe((user: firebase.User) => {
if (user) {
this.getUserData(user.uid);
}
});
发生了什么,为什么我的解决方案有效?
【问题讨论】:
-
如果你这样做会发生什么:
const user = await this.fireAuth.authState.pipe(first()).toPromise();? -
有趣的是,我在几分钟前也发现了这种方法。但是为什么我需要使用
pipe(first())?我更新了问题,随时回答这个问题
标签: angular typescript async-await firebase-authentication google-cloud-firestore