尝试获取Firebase用户身份验证的状态

时间:2020-08-25 07:54:10

标签: javascript firebase firebase-authentication

我有一个使用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)

2 个答案:

答案 0 :(得分: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中,您可以从return.then()方法中提取.catch()个值,然后在代码中进一步使用该解析值。

答案 1 :(得分:0)

如果您想知道用户何时登录,无论他们如何登录,都应该使用auth状态观察器来设置一个回调,该回调将在用户登录或注销时被调用,例如在documentation中显示:

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