【问题标题】:cant write to firestore database before firebase authentication angular app在firebase身份验证角度应用程序之前无法写入firestore数据库
【发布时间】:2018-10-28 02:48:27
【问题描述】:

我正在编写一个有角度的应用程序。我有两个服务(认证服务)和(注册服务)。我的注册服务将用户数据(例如姓名和电子邮件)写入 Firestore,而我的身份验证服务(从注册中获取电子邮件和密码)在我的注册服务将用户数据写入 Firestore 后创建一个用户帐户。这应该是一个相对简单的过程。问题是,我的 authservice 设法创建了一个用户帐户,但我的注册服务没有写入数据库。当我评论对身份验证服务的调用时,注册服务会设法写入数据库。

认证服务

this.afs.auth.createUserWithEmailAndPassword(user.email,user.pass)

注册服务

this.afs.collection('path').add({
  firstName: rUser.firstName,
  lastName: rUser.lastName,
  email: rUser.email
}).catch(function (error) {
  console.log(error)
})

现在这两个服务都可以正常工作,但是在调用 auth 服务时注册服务不起作用。

我到处搜索,但没有解决方案。

这是我对这两个服务的调用

this.rSERVICE.saving(registeredUser);
this.authService.signUpUser(registeredUser);

【问题讨论】:

  • 我认为您的 authService.signUpUser 应该在 rService.saving 调用成功完成后调用。一种方法是让您的保存函数返回一个承诺并将您的 singUpUser 放入 .then() 块中。如果您仍需要示例,请告诉我。
  • 谢谢。那行得通!但我没有添加 .then,而是添加了一个 await rService.saving,它在保存到数据库后运行。
  • 很高兴知道这一点。 Await 很好,但您也应该确保您的注册成功并处理错误。你要我写一个你可以接受的答案吗?
  • 是的。您的解决方案是完美的!谢谢
  • 如果您认为是这样,请单击解决方案并接受它,因为正确答案是承认和帮助可能遇到相同问题的其他人的一种方式。谢谢。

标签: angular firebase-realtime-database firebase-authentication google-cloud-firestore


【解决方案1】:

因为注册是async的任务,所以在调用注册任务之前,请确保这个任务已经成功完成。

实现的一种方法是让saving 函数返回一个promise 并在其.then() 块内调用signUpUser。像这样:

registration.service

// saving function return a promise
  saving(user: User): Promise<boolean> {
    return new Promise(
        (resolve) => {
            this.afs.auth.createUserWithEmailAndPassword(user.email, user.pass)
                .then(() => { resolve(true); })
                .catch((error) => {
                  console.log(error);
                  throw new Error("Some error message here...");
                })})
  }

使用服务

this.rSERVICE.saving(registeredUser)
    .then(() => { this.authService.signUpUser(registeredUser); })
    .catch(error => { console.log(error); });

【讨论】:

    猜你喜欢
    • 2022-08-06
    • 2020-02-13
    • 2018-07-02
    • 1970-01-01
    • 2020-03-12
    • 2017-11-11
    • 2020-11-21
    • 1970-01-01
    • 2020-09-27
    相关资源
    最近更新 更多