成功登录后 firebase.auth().CurrentUser.uid 为 null [英] firebase.auth().CurrentUser.uid is giving null after successful login
问题描述
我使用了 firebase 登录.它正在成功登录.我在登录页面配置文件中有四个页面,包括销售、购买和关于我们.当我在个人资料和销售页面中检索当前用户的 uid 值时.但是我在购买页面上显示为空,为什么会这样?
I have made use of firebase login. It is logging in successfully. I have four pages inside login page profile, sell, buy and about us. When I am retrieving the value of current user's uid in profile and sell page. But i am getting null in buy page why is it so?
JS对于用户页面
function save_user()
{
const uid = document.getElementById('user_id');
const userpwd = document.getElementById('user_pwd');
const btnregister=document.getElementById('btn-action');
//btnregister.addEventListener('click', e=>
//{
const email=uid.value;
const pass=userpwd.value;
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
console.log(error.Message);
});
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
window.location='userpage.html';
}
});
JS
对于 firebase.auth().currentUser.uid 显示空代码的购买页面
for buy page where firebase.auth().currentUser.uid is showing null code
var fbRef = firebase.database().ref().child("Sell_Products");
var user = firebase.auth().currentUser.uid;
alert(user); /*Here it's showing null
fbRef.on("child_added", snap => {
var key=snap.key;
alert('HEllo');
alert(key);
var name = snap.child("name").val();
var price = snap.child("price").val();
var category = snap.child("category").val();
var description = snap.child("description").val();
var image = snap.child("image").val();
$("#ex-table").append("<tr><td><a href="auction.html?itemKey="+key+""><img src=" + image + "/img></a></td><td>" + name + "</td><td>" + price + "</td><td>" + category + "</td><td>" + description + "</td></tr>" );
});
推荐答案
我也遇到过这样的问题.实际上,在 auth 未初始化之前,它无法显示一些数据,但是当我们使用 firebase.auth().CurrentUser
时,它甚至在 auth 初始化之前获取数据.您可以在代码中设置超时,直到身份验证完全初始化.
I also encountered such problem. Actually, until the auth is not initialized, it cant show some data but when we use firebase.auth().CurrentUser
, it fetches data even before the auth is initialized. You can set a timeout in the code until the auth is completely initialized.
我使用这种方法来获取数据.
I used this approach to get the data.
const authPromise=()=>{
return new Promise((resolve,reject)=>{
const user = firebase.auth().currentUser;
console.log(user.email)
})
}
setTimeout(authPromise,2000)
这篇关于成功登录后 firebase.auth().CurrentUser.uid 为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!