我使用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
});
答案 0 :(得分:1)
createUserWithEmailAndPassword()
返回所谓的承诺。承诺可以成功并且失败,并且每个承诺都有单独的条款。您可以使用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.
}
});