2016-12-30 21 views
2

我開發了一些使用Firebase的應用程序。隨着時間的推移,我意識到我重複了很多不必要的代碼,並決定創建一個小型庫來幫助我提高生產力。就在開始的時候,我試圖創建該對象在Javascript:創建基本庫的Firebase錯誤

read.childRoot = function(att) { 
    var acessChildRoot = firebase.database().ref("root/"); 
    acessChildRoot.once('value').then(function(snapshot) { 
     alert(snapshot.child("nome").val()); 
    }); 
} 

我試圖通過這行代碼來訪問:

alert(read.childRoot("nome")); 

所以我能讀我想要的參考,但第一個回報是未定義的值。我如何過濾這個值並顯示我真正想看到的值?

回答

3

看來你想等待在節點上設置第一個值。

在這種情況下,我建議使用這個片段(來自my gist):

var listener = ref.on('value', function(snapshot) { 
    if (snapshot.exists()) { 
     console.log('Value is now '+snapshot.val()); 
     ref.off('value', listener); 
    } 
});