【问题标题】:Trying to get the status of firebase user authentication试图获取firebase用户身份验证的状态
【发布时间】:2020-12-13 21:07:54
【问题描述】:

我有一个使用 firebase 的身份验证功能,它只是 firebase 文档中的身份验证代码

export const signIn = (email,password) => {
   firebase.auth().signInWithEmailAndPassword(email, password).then(()=>{
       alert('Sign in Successful!')
    }).catch(function(error) {
        alert(error.message)
    });
}

我这样称呼它

signIn(mail, password)

当我在我的代码中调用它时,它可以完美运行并且会出现正确的警报。但是,如果用户成功登录或未成功登录,我想从我的身份验证功能中实际接收一些东西,例如 True 或 False。有没有办法让我从我的函数或任何解决方法中接收这个值?

//evaluates to True if logged in successfully and vice versa
let authState = signIn(this.mail, this.password)

【问题讨论】:

    标签: javascript firebase firebase-authentication


    【解决方案1】:

    您可以采取几种方法,首先想到的是:

    export const signIn = (email, password) => {
      return firebase.auth().signInWithEmailAndPassword(email, password).then(userCredential => {
        alert('Sign in Successful!');
        return true;
      }).catch(error => {
        alert(error.message);
        return false;
      });
    }
    
    // ......
    
    let authState = await signIn(this.mail, this.password);
    

    promises 中,您可以从.then().catch() 方法中获取return 值,然后在代码中进一步使用该解析值。

    【讨论】:

    • 这很好用!谢谢!是否需要 .then() 中的响应?当我把它排除在外时,它似乎可以工作
    • 不,这不是必需的,我只是更喜欢适当地命名我的回调而不是将其留空。如果任何给出的答案解决了您的问题,请记住将其标记为正确的解决方案。
    【解决方案2】:

    如果您想知道用户何时登录,无论他们是如何登录的,您都应该使用身份验证状态观察器来设置一个回调,该回调将在用户登录或退出时调用,如显示在documentation:

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

    【讨论】:

    • 我的用例中的问题是,当用户登录时,我希望能够在您提供的函数范围之外编辑变量,而我无法通过此设置真正做到这一点.
    • 您当然可以使用某种形式的数据共享或依赖注入来对回调范围之外的用户对象进行操作。事实上,身份验证状态观察者是挂钩登录和注销状态的首选方式,并且在所有平台上都像这样使用。是的,它确实改变了你的程序的形状,但是这种异步的“反应式”编程是新常态。
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2017-12-05
    • 1970-01-01
    • 2021-07-30
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    相关资源
    最近更新 更多