将值推送到数组会在末尾添加未定义

时间:2017-07-31 12:36:34

标签: javascript arrays json angular firebase

我从Firebase提取数据。我想提取值并将它们保存在数组中。之后,我将在我的应用程序中将该数组值用作字符串。问题是当我将值从DB推送到数组时,它会在数组末尾添加undefined。当我想看到数组的值(carUserDetails [0])时,它返回undefined,但是应该返回一个字符串" BMW"

var UserID = firebase.auth().currentUser.uid;
var refModels = firebase.database().ref("/users/" + UserID);

var carUserDetails = [];

refModels.once('value').then(function (snapshot) {
    snapshot.forEach(function (childSnapshot) {
        var usersValue = childSnapshot.val(); //get the values of the object
        carUserDetails.push(
            usersValue.carMake, 
            usersValue.carYear, 
            usersValue.carModel, 
            usersValue.carTrim
        );
    });
});

console.log(carUserDetails);

enter image description here

console.log(carUserDetails[0]) // returns undefined too

那可能是什么问题

2 个答案:

答案 0 :(得分:1)

我认为这是因为你太早调用console.log记得读取firebase值是异步的。您应该将控制台放在function (snapshot)内和snapshot.forEach

之后
refModels.once('value').then(function (snapshot) {
  snapshot.forEach(function (childSnapshot) {
    ....
  });
  console.log(carUserDetails);
});

答案 1 :(得分:0)

所以是异步调用问题。请参阅修复

var UserID = firebase.auth().currentUser.uid;
var refModels = firebase.database().ref("/users/" + UserID);

var carUserDetails = [];

refModels.once('value').then(function (snapshot) {
  snapshot.forEach(function (childSnapshot) {
    var usersValue = childSnapshot.val(); //get the values of the object
    carUserDetails.push(
        usersValue.carMake, 
        usersValue.carYear, 
        usersValue.carModel, 
        usersValue.carTrim
      );
     });

     $scope.getValueFromArray(); //call function here

    });



$scope.getValueFromArray = function(){

   console.log(carUserDetails[0]); returns "BMW"
 }