snapshot.key到字符串变量?

时间:2017-07-18 21:34:05

标签: javascript firebase firebase-realtime-database

我试图将变量设置为snapshot.key值。到目前为止,我的变量返回interlocutor = [object Promise],但我想将其设置为实际值,例如SEV9iTd8whgf0VyIbqUiVNaTcAL2,它是节点的关键。 我怎么能这样做?

谢谢!

这是我的代码:

this.interlocutor = this.getRandomInterlocutor();


  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.orderByChild('order').equalTo(randomIndex).on('value', function(userSnapshot) {
    userSnapshot.forEach(function(userSnapshot) {
        this.interlocutor = userSnapshot.key;
        return val.userSnapshot.key;
        });
    });
  }

1 个答案:

答案 0 :(得分:0)

var ref = firebase.database().ref('Comapanies/'+'Company/'+'User/');
ref.orderByChild('order').equalTo(1).on('value', function(userSnapshot) {
    userSnapshot.forEach(function(userSnapshot) {
        //this.interlocutor = userSnapshot.key;
       document.getElementById("Key").innerHTML= userSnapshot.key
    });
});

在此处查看我的工作示例Js Fiddle Sample