我正在尝试获取用户 UID 来代替 Firebase/Firestore 中自动生成的文档 ID,但由于此错误而无法获取它
类型错误:firebase.auth(...).currentUser 为 null
这是我的 index.js 文件:-
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail, txtPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
//alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
// Getting user id
var uid = firebase.auth().currentUser.uid;
//User Data Insertion
if(uid !=null){
db.collection("users").doc(uid).add({
UserName: txtname,
Email: txtEmail,
Password: txtPass
})
// .then(function(uid) {
// console.log("Document written with ID: ", uid);
// })
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
}
Since firebase.auth().createUserWithEmailAndPassword(...)
是一个异步函数,您必须等待它解析才能继续。
你可以试试这个:
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail,txtPass)
.then(function (user) {
// insert any document you want here
})
.catch(function(error) {
// handle error here
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)