0

林试图检索从火力DB用户,但是当我打印snapshot.val()它显示[对象的对象。我怎样才能打印真实的数据?谢谢!火力地堡snapshot.val()返回的翻译:

FriendlyChat.prototype.getRandomInterlocutor = async function(){ 
 
var numberOfUsers = await this.getNumberOfUsersRef(); 
 

 
var randomIndex = Math.floor(Math.random() * numberOfUsers); 
 
if(randomIndex == 0){ 
 
    randomIndex = 1; 
 
} 
 

 
var ref = await firebase.database().ref('companies/' + this.company + '/users/'); 
 
ref.limitToFirst(randomIndex).once('value').then(snapshot => 
 
{ 
 
    var user = snapshot.val(); 
 
    console.log('getRandomInterlocutor = ' + user); 
 
    return user; 
 
}); 
 
    } 
 

 
FriendlyChat.prototype.onAuthStateChanged = function(user) { 
 
    console.log('entro a onAuthStateChanged'); 
 
    this.interlocutor = this.getRandomInterlocutor(); 
 
    console.log(this.interlocutor); 
 
}

+0

just console.log(user)找到用户对象的结构。 – error404

回答

0

只需打印console.log(user);,而不是在它的OBJ的字符串。 此重现:

var obj = [{a: 1}, {a: 'lucas', b: 2}]; 
console.log('current obj', obj); 

然而,由于用户是一个数组,你可以做到这一点,你想让它变得每个客体。 (ES6)

user.forEach((u, key) => { 
    // u contains your user data object which is like u.uid and u.email or whatever keys you got. 
    console.log(key, 'key here contains the strange "firebase array index key"'); 
    console.log(u); 
}); 
+0

谢谢,但我很困惑。它打印对象{SEV9iTd8whgf0VyIbqUiVNaTcAL2:Object}。我如何设置变量='SEV9iTd8whgf0VyIbqUiVNaTcAL2'? – Ace

+0

那是因为火力得到了奇怪的阵列,其状物体,而不是数组,这样'SEV ...'是下面对象的关键,而不是因为你有规则排列的索引。所以,你需要喜欢写'用户[“SEV9iTd8whgf0VyIbqUiVNaTcAL2”]'来获得用户。我知道它的奇怪的开始,但随着越来越多的,你使用它更“清晰的”它变得 –

+0

此博文是一个很好的资源,了解火力阵列更好:https://firebase.googleblog.com/2014/04/best -practices阵列合firebase.html –