【问题标题】:Async method does not return a value and is stuck异步方法不返回值并卡住
【发布时间】: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


【解决方案1】:

toPromise() 创建一个将在流完成时解析的承诺。

因此,如果this.fireAuth.authState 从未完成,但发出值,您可以使用first 运算符创建一个在第一个发出值之后完成的流。这样,promise 就解决了。

另一方面,订阅处理程序会为每个值调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 2014-10-22
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多