2016-09-16 92 views
0

我使用firebase啓動我的web應用程序,然後向數據庫添加新數據:{'title':'hello world!'}。然後我試圖得到這樣的數據:database.ref().child('title')和我奇怪的物體: enter image description here從firebase中獲取數據不起作用

我的代碼:

export class App extends Component { 

    constructor(props) { 
     super(props); 

     // Initialize Firebase 
     var config = { 
      apiKey: "&&&&&&&dbBJY_ie3CbXtnL6M6QBEL2JqWI", 
      authDomain: "&&&&&&&.firebaseapp.com", 
      databaseURL: "&&&&&test-61197.firebaseio.com", 
      storageBucket: "test-&&&&.appspot.com", 
      messagingSenderId: "7&&&1193299" 
     }; 
     firebase.initializeApp(config); 

     // Get a reference to the database service 
     var database = firebase.database(); 

     console.log(database.ref().child('title')); 

    } 

    login() { 
     console.log('login'); 
     // Log the user in via Twitter 

    } 

    render() { 
    return (
     <View style={styles.container}> 
      <Touchable style={styles.loginBtn} onPress={ this.login }> 
       <Text style={styles.loginBtnText}>login</Text> 
      </Touchable> 
     </View> 
    ); 
    } 
} 

如何得到我的數據? Firebase版本:3.4.0

+0

你能告訴我們你的代碼嗎?我的猜測是你必須在該對象上調用'.val()'。 – yihangho

+0

是的,這是我的代碼:[jsfiddle link](https://jsfiddle.net/1mxc9zsg/) – Slava

回答

2

火力地堡查詢是異步的。因此,您需要註冊一個回叫,以便Firebase在結果準備就緒時通知您。

試試這個:

database.ref().child('title').on('value', (snapshot) => { 
    console.log(snapshot.val()); 
}); 

您可以爲更多的信息,請閱讀this

+0

它適用於我。 – Slava

2

在Firebase中有兩種檢索數據的方式。首先是要等待一個事件對你的實時數據庫使用偵聽發生:

var myTitleRef = database.ref('title'); 
    myTitleRef.on("value",function(snapshot){ 
    //snapshot contains the data you're looking for 
    HandleTitle(snapshot); 
    }); 

另一種方法是調用您的數據的REST GET,在這種情況下,你需要在DB的整個網址,並添加「 .json「結尾。在這個例子中,我會使用jQuery:

var myurl = pathToYourDatabase + 'title.json'; 
$.ajax({ 
      url: myurl, 

      jsonp: "callback", 
      dataType: "jsonp", 
      success: function(response) { 
       //Response contains data 
       DoSomethingWithTitle(response); 
      } 
     }); 

欲瞭解更多信息,請閱讀文檔: https://firebase.google.com/docs/web/setup

0

引用是空數據庫不被稱爲

例子:

正確的做法:

var data = database().ref('/your root destination').child('title'); 

你失蹤數據庫後()

更新: 您的代碼和我上面演示的代碼實際上是創建一個數據庫條目。

我們瞭解這個項目獲取的數據:

data.once('value').then(function(snapshot) { 
    var objectData = snapshot.val(); 

}); 

希望這有助於

+0

'.ref'方法的參數是可選的。如果沒有指定,則會返回根的引用。請參閱https://firebase.google.com/docs/reference/js/firebase.database.Reference – yihangho

+0

如果我們假設孩子的「標題」是根的直接後代,則正確... – KpTheConstructor

+0

對,這是真的。我誤解你的答案,聲稱'。ref()'不起作用。 – yihangho