【问题标题】:Firebase SDK (Web) create a password-based accountFirebase SDK (Web) 创建基于密码的帐户
【发布时间】:2016-07-20 03:50:15
【问题描述】:

我使用 Firebase SDK (Web) 进行用户登录。

这是一个链接

Authenticate with Firebase using Password-Based Accounts

我使用此代码创建用户帐户,我可以成功创建用户。

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
});

但我的问题是如何决定是否创造成功?

如果创建失败,代码可以捕获错误,但如果成功,我如何捕获?

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
}.catch(success){
  // Handle Success here
  // I want to catch success like this
});

【问题讨论】:

    标签: javascript web firebase firebase-authentication


    【解决方案1】:

    createUserWithEmailAndPassword() 返回一个所谓的承诺。一个promise可以成功也可以失败,并且每个promise都有单独的子句。您可以使用then() 子句处理成功:

    firebase.auth().createUserWithEmailAndPassword(email, password).then(success){
      // Handle Success here
    }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
    };
    

    您在文档中没有看到then() 的原因是上面遗漏了用户登录时的一些重要流程。

    例如:如果您重新加载页面/应用程序会发生什么? Firebase 会自动将用户的会话保存到本地存储,但代码并没有意识到这一点。因此,您的应用可能会要求用户重新登录,从而导致体验不太好。

    如果使用 Firebase 身份验证,最好使用 monitor the authentication state:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // No user is signed in.
      }
    });
    

    当用户登录或退出时,不会自动调用此回调。因此,无论您创建了帐户,他们重新加载了页面还是刷新了他们的短期令牌 - 第一个块中的代码都将执行。类似的:无论用户的会话是否过期、他们退出或出于其他原因退出 - 第二个块中的代码都会运行。

    这样,您只有一个地方来处理用户登录或退出的情况。

    但由于createUserWithEmailAndPassword() 可能会以各种惊人的方式失败,您仍然需要明确地处理这些错误。

    因此,处理createUserWithEmailAndPassword() 和监控登录状态的完整惯用代码是:

    firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
    };
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // No user is signed in.
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 2019-06-18
      • 2021-09-25
      • 2014-06-27
      • 2021-08-15
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多