gpt4 book ai didi

javascript - Firestore在其他功能中获取用户ID

转载 作者:行者123 更新时间:2023-11-28 17:38:28 26 4
gpt4 key购买 nike

我正在使用 firestore 数据库创建一个应用程序。我有一个问题,我想在其他功能中访问用户 ID,我该怎么做?

我正在使用 firebase.auth().onAuthStateChanged 函数查看用户是否已登录,我可以在此处访问用户 ID。

当我点击 btnName 时如何访问它?现在我必须遵循以下错误:

Uncaught 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))
});

最佳答案

您可以使用firebase.auth().currentUser获取当前登录的用户,查看此代码

btnName.addEventListener('click', e => {
let user = firebase.auth().currentUser;
console.log(user);
if (user) {
console.log(db.collection("users").doc(user.uid))
} else {
alert('user not logged in')
}
});

关于javascript - Firestore在其他功能中获取用户ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48535102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com