使用firestore数据库创建应用程序。我有一个问题,我想在其他功能中访问用户ID,我该怎么办?
我正在使用firebase.auth()。onAuthStateChanged函数 观察用户是否已登录,我可以在此处访问用户ID。
点击btnName后如何访问它?现在我必须遵循错误:
未捕获的ReferenceError:未定义uid
HTML
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, width=device-width, maximum-scale=1.0" />
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-firestore.js"></script>
</head>
<body>
<h1>Welcome</h1>
<button id="btnLogout" class="hide">Logout</button>
<br><br>
<input id="txtName" type="" placeholder="Name">
<button id="btnName">Add name</button>
<script src="js/app.js"></script>
</body>
</html>
JS
// Initialize Firebase
var config = {
apiKey: "AIzaSyBAQYQxSU0JkskvXKqBKzAHHWViutuP_lg",
authDomain: "crypto-3171a.firebaseapp.com",
databaseURL: "https://crypto-3171a.firebaseio.com",
projectId: "crypto-3171a",
storageBucket: "crypto-3171a.appspot.com",
messagingSenderId: "86923986632"
};
firebase.initializeApp(config);
const db = firebase.firestore();
const txtName = document.getElementById('txtName');
const btnName = document.getElementById('btnName');
// log user out of app
btnLogout.addEventListener('click', e => {
firebase.auth().signOut();
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
addToUsers(user)
} else {
}
});
// add users to database 'users'
function addToUsers(user) {
var email = user.email;
var uid = user.uid;
var users = db.collection("users").doc(uid);
users.set({
email: email,
id: uid
});
}
// when user clicks add name to 'users' document
btnName.addEventListener('click', e => {
console.log(db.collection("users").doc(uid))
});
答案 0 :(得分:3)
您可以使用firebase.auth().currentUser
获取当前登录用户,结帐此代码
btnName.addEventListener('click', e => {
let user = firebase.auth().currentUser;
console.log(user);
if(user)
console.log(db.collection("users").doc(uuser.uid))
else
alert('user not logged in')
});