问题描述
这是我的网页
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calcolo Diliuzioni</title>
</head>
<body>
<h1>My app</h1>
<!-- Libreria per gestire l'autenticazione con google -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<!-- Firebae config -->
<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
storageBucket: "",
};
firebase.initializeApp(config);
</script>
<script type="text/javascript">
var user = firebase.auth().currentUser;
if (user) {
console.log(user);
} else {
console.log(user);
}
</script>
</body>
</html>
假设我有一个已经登录的用户.当我在控制台中加载页面时,我得到 null
.虽然我期待拥有当前用户的对象.
Let's assume I have an already logged user. When I load the page in the console I got null
. While I'm expecting to have the current user's object.
如果我在浏览器控制台中运行相同的代码
If I run the same code in the browser console
var user = firebase.auth().currentUser;
if (user) {
console.log(user);
} else {
console.log(user);
}
我能够获取当前用户的对象.
I'm able to get the current user's object.
我认为 firebase.initializeApp(config);
有一些异步行为.解决它的正确方法是什么?我应该在 firebase.initializeApp(config);
函数上使用 promise 或其他东西吗?一种回调..
I think that the firebase.initializeApp(config);
has some async behavior. What's the right way to work around it? Should I use a promise or something on the firebase.initializeApp(config);
function? A sort of callback..
推荐答案
初始化应用是同步的.但是,确定当前用户状态是异步的.确定当前身份验证状态的正确方法是使用观察者:https://firebase.google.com/docs/auth/web/manage-users
initialize app is synchronous. However, determining the current user state is asynchronous. The right way to determine the current auth state is to use an observer: https://firebase.google.com/docs/auth/web/manage-users
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in and currentUser will no longer return null.
} else {
// No user is signed in.
}
});
这篇关于firebase.initializeApp 回调/承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2