2017-07-12 22 views
1

我正在構建一個從Firebase數據庫獲取其對象的應用程序。問題是,當我嘗試迭代我所得到的內容時,它不顯示任何內容。但是,當我要求通過console.log顯示它時,它就在那裏! 我想這是因爲HTTP方法及其承諾。但我還沒有想出如何解決它。有人能幫我理解嗎?Angular JS - 從Firebase數據庫中獲取對象的迭代陣列

HTML:

<table class="table"> 
    <thead> 
    <tr> 
     <th>ID</th> 
     <th>Name</th> 
     <th>Description</th> 
     <th>Price</th> 
     <th>Options</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr ng-repeat="profile in profiles"> 
     <td>{{profile.value.id}}</td> 
     <td>{{profile.value.name}}</td> 
     <td>{{profile.value.description}}</td> 
     <td>{{profile.value.price | currency}}</td> 
     <td> 
     <button type="button" class="btn">Edit</button> 
     <button type="button" class="btn btn-danger">Delete</button> 
     </td> 
    </tr> 
    </tbody> 
</table> 

Controller.js

App.controller("adminController", function($scope) { 
    console.log("running"); 

    var profiles = new Array; 

    var query = firebase.database().ref("profiles").orderByKey(); 

    query.once("value") 
    .then(function(snapshot) { 
     snapshot.forEach(function(childSnapshot) { 
     var key = childSnapshot.key; 
     var childData = childSnapshot.val(); 

     profiles.push({ 
      key: key, 
      value: JSON.parse(childData) 
     }) 
    }); 
    console.log(profiles); 
    }); 
} 
+0

數據被添加到'profiles'在AngularJS不期待它的那一刻。將回調包裝在'$ timeout()'中以使其知道。看到我的答案在這裏:https://stackoverflow.com/questions/31496266/angular-js-firebase-child-added-not-rendering-on-page/31496985#31496985 –

回答

2

您需要使用$scope.profiles與您的控制器,

App.controller("adminController", function($scope) { 
    console.log("running"); 
    $scope.profiles = []; 
    var query = firebase.database().ref("profiles").orderByKey(); 
    query.once("value") 
    .then(function(snapshot) { 
     snapshot.forEach(function(childSnapshot) { 
     var key = childSnapshot.key; 
     var childData = childSnapshot.val(); 
     $scope.profiles.push({ 
      key: key, 
      value: JSON.parse(childData) 
     }) 
    }); 
    console.log($scope.profiles); 
    }); 
} 
+0

我修正了你說的,但現在我得到這個消息在控制檯上:'未捕獲(承諾)TypeError:無法讀取未定義的'push'屬性。如果我在推送前啓動它,它會顯示一個空的數組:( –

+0

)當我按照上面的方法推送它時,檢查值是否爲 – Sajeetharan

+0

,它會在幾秒鐘後顯示結果(可能由於HTTP承諾)。但是,如果我將它推入'$ scope.profiles',它會給出一個錯誤,我可能正在努力使用HTTP方法,並且自己傾斜 –