Firebase 数据库 console.log() 在 Javascript 中返回 Null

Firebase Database console.log() returning Null in Javascript

如果可能的话,我希望寻求帮助。在下面的代码中。我正在尝试 console.log() 来自 My Firebase 参考的数据,您可以在下面的代码中看到。但是 Console.log() 返回 null 而不是 Firebase 实时数据库中的值。我还提供了运行良好的添加代码。如果有帮助,请查看我的数据库图像。除了返回 null 之外,我的控制台中没有收到任何其他错误。

function addFamilyMember() {
  var NameOfMember = document.getElementById("newFamilyMemberName").value;
  var DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
  var EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
  var ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;

 if (
  NameOfMember.length == "" ||
  DoBOfMember.length == "" ||
  EmailOfMember.length == "" ||
  ContactOfMember.length == ""
) {
   alert("Please enter all details of your Family Member");
} else {
   var user = firebase.auth().currentUser;
   var uid;
   if (user != null) {
     uid = user.uid;
   }

firebase
  .database()
  .ref("/Users/" + uid + "/Family/" + NameOfMember)
  .set({
    MemberName: NameOfMember,
    MemberDOB: DoBOfMember,
    MemberEmail: EmailOfMember,
    MemberContact: ContactOfMember,
  });
 }
}

var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}

firebase
  .database()
  .ref("/Users/" + uid + "/Family/")
  .on("value", function (snap) {
    var mName = snap.child("MemberName").val();
    var mDOB = snap.child("MemberDOB").val();
    var mEmail = snap.child("MemberEmail").val();
    var mContact = snap.child("MemberContact").val();

    console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
});

问题是您正在获取整个 Family 节点并试图访问每个成员的数据。 我试图重新创建您的数据库结构,并在 运行 代码的控制台中得到了这个。

{
  "Name One": {"MemberContact":10000,"MemberName":"Name Two"},
  "Name Two": {"MemberContact":10002,"MemberName":"Name Two"}
}

因此,如果您想从中获取每个用户的数据,请尝试以这种方式使用 forEach

Object.keys(snap.val()).forEach(key => {
  const memberData = snap.val()[key]
  //Data of each member
  var mName = memberData["MemberName"]
  var mDOB = memberData["MemberDOB"]
  var mEmail = memberData["MemberEmail"]
  var mContact = memberData["MemberContact"]
  console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
})

首次加载页面时,不应使用 firebase.auth().currentUser,因为 Firebase Auth 需要 check if the user's login session is valid first

let currentUserFamilyRef = null;

// for use with .on("value") and .off("value")
function onValueFamilyListener(snapshot) {
  const familyMembers = [];
  snapshot.forEach((familyMemberSnapshot) => {
    const MemberName = snap.child("MemberName").val();
    const MemberDOB = snap.child("MemberDOB").val();
    const MemberEmail = snap.child("MemberEmail").val();
    const MemberContact = snap.child("MemberContact").val();
    
    familyMembers.push({ MemberName, MemberDOB, MemberEmail, MemberContact });

    console.log(MemberName + " " + MemberDOB + " " + MemberEmail + " " + MemberContact);
  }

  // TODO: do something with the array of family members familyMembers
}

// for showing loading state
function showLoadingIcon(visible) {
  if (visible) {
    // TODO: show the icon
    // TODO: disable the submit button
  } else {
    // TODO: hide the icon
    // TODO: enable the submit button
  }
}

// for when addFamilyMember() is called while signed out
function addFamilyMemberSignedOut() {
  alert('You need to sign in first!');
  return false;
}

// for when addFamilyMember() is called while signed in
function addFamilyMemberSignedIn() {
  const NameOfMember = document.getElementById("newFamilyMemberName").value;
  const DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
  const EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
  const ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;

  if (
    NameOfMember.length == "" ||
    DoBOfMember.length == "" ||
    EmailOfMember.length == "" ||
    ContactOfMember.length == ""
  ) {
    alert("Please enter all details of your Family Member");
    return false;
  }
  
  const user = firebase.auth().currentUser;
  
  if (user === null) {
    // shouldn't get here, but just in case.
    alert('You need to sign in first!');
    return false;
  }
  
  const uid = user.uid;
  
  showLoadingIcon(true);

  firebase
    .database()
    .ref("/Users/" + uid + "/Family/" + encodeURIComponent(NameOfMember)) // escape names as they may contain symbols, etc.
    .set({
      MemberName: NameOfMember,
      MemberDOB: DoBOfMember,
      MemberEmail: EmailOfMember,
      MemberContact: ContactOfMember,
    })
    .then(
      () => {
        // saved family member's data successfully
        showLoadingIcon(false);
        // reset form
        document.getElementById("newFamilyMemberName").value = "";
        document.getElementById("newFamilyMemberDoB").value = "";
        document.getElementById("newFamilyMemberEmail").value = "";
        document.getElementById("newFamilyMemberContactNo").value = "";
        alert('Information saved!');
      },
      (err) => {
        // failed to save family member's data
        showLoadingIcon(false);
        // err.code may lead to more specific error information
        console.error(err);
        alert('Failed to save information!');
      }
    );
}

// for calling the correct addFamilyMember version
let addFamilyMember = addFamilyMemberSignedOut;

showLoadingIcon(true); // while loading the user's info, show a loading icon

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // A user is (newly/already) signed in.
    // create a reference for this user's family
    const newUserFamilyRef = firebase.database()
      .ref("/Users/" + user.uid + "/Family");
    if (currentUserFamilyRef !== null) {
      // if the old user and new user are the same, do nothing
      // but if they've changed, remove the old listener and update currentUserFamilyRef
      if (!currentUserFamilyRef.isEqual(newUserFamilyRef)) {
        currentUserFamilyRef.off("value", onValueFamilyListener);
        currentUserFamilyRef = newUserFamilyRef;
      }
    } else {
      currentUserFamilyRef = newUserFamilyRef;
    }
    // use the "signed in" version of addFamilyMember
    addFamilyMember = addFamilyMemberSignedIn;
    // attach listener to "/users/{user.uid}/Family"
    currentUserFamilyRef.on("value", onValueFamilyListener);
  } else {
    // no user is signed in.
    // use the "not signed in" version of addFamilyMember
    addFamilyMember = addFamilyMemberSignedOut;
    // if a user was logged in, clean up it's listener to prevent errors
    if (currentUserFamilyRef !== null) {
      currentUserFamilyRef.off("value", onValueFamilyListener);
    }
    // no user, so set the reference to null
    currentUserFamilyRef = null;
  }
  showLoadingIcon(false);
});

您不能直接使用 firebase.auth().currentUser。首先,您需要检查用户的身份验证状态。那么只有你可以请求当前用户。所以要做到这一点,你需要使用身份验证状态包装它 observer.You 可以在 firebase 文档上阅读更多关于它的信息:[https://firebase.google.com/docs/auth/web/start][1]

function addFamilyMember() {
    var NameOfMember = document.getElementById("newFamilyMemberName").value;
    var DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
    var EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
    var ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;
  
firebase.auth().onAuthStateChanged((user) => {
if (user) {
   if (
    NameOfMember.length == "" ||
    DoBOfMember.length == "" ||
    EmailOfMember.length == "" ||
    ContactOfMember.length == ""
  ) {
     alert("Please enter all details of your Family Member");
  } else {
     var user = firebase.auth().currentUser;
     var uid;
     if (user != null) {
       uid = user.uid;
     }
  
  firebase
    .database()
    .ref("/Users/" + uid + "/Family/" + NameOfMember)
    .set({
      MemberName: NameOfMember,
      MemberDOB: DoBOfMember,
      MemberEmail: EmailOfMember,
      MemberContact: ContactOfMember,
    });
   }
  }
  
  var user = firebase.auth().currentUser;
  var uid;
  if (user != null) {
  uid = user.uid;
  }
  
  firebase
    .database()
    .ref("/Users/" + uid + "/Family/")
    .on("value", function (snap) {
      var mName = snap.child("MemberName").val();
      var mDOB = snap.child("MemberDOB").val();
      var mEmail = snap.child("MemberEmail").val();
      var mContact = snap.child("MemberContact").val();
  
      console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
  })
})}