这是我的网页
<!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.虽然我期望拥有当前用户的对象.
如果我在浏览器控制台中运行相同的代码
var user = firebase.auth().currentUser; if (user) { console.log(user); } else { console.log(user); }
我能够获得当前用户的对象.
我认为是firebase.initializeApp(config);有一些异步行为.什么是解决它的正确方法?我应该在firebase.initializeApp(config)上使用promise还是其他东西;功能?一种回调..
解决方法
初始化应用程序是同步的.但是,确定当前用户状态是异步的.确定当前身份验证状态的正确方法是使用观察者:
https://firebase.google.com/docs/auth/web/manage-users
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. } });