【问题标题】:Angular JS - Iterate array of objects obtained from a Firebase database [duplicate]Angular JS - 迭代从 Firebase 数据库获得的对象数组[重复]
【发布时间】:2017-07-12 01:16:09
【问题描述】:

我正在构建一个从 Firebase 数据库获取其对象的应用。问题是当我尝试迭代我得到的东西时,它什么也没显示。但是,当我要求通过console.log 显示它时,它就在那里! 我猜这是因为 HTTP 方法及其承诺。但我还没有想出如何解决它。有人可以帮我理解吗?

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);
  });
}

【问题讨论】:

标签: javascript angularjs firebase firebase-realtime-database


【解决方案1】:

您需要在控制器中使用 $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);
  });
}

【讨论】:

  • 我按照你的说法修复了它,但现在我在控制台上收到了这条消息:Uncaught (in promise) TypeError: Cannot read property 'push' of undefined。如果我在推送之前启动它,它会显示一个空数组:(
  • 检查是否有值
  • 当我像上面写的那样推送它时,它会在几秒钟后显示结果(可能是由于 HTTP 承诺)。但是,如果我将其推入$scope.profiles,则会出现错误。我可能正在为 HTTP 方法和角度本身而苦苦挣扎
  • 可能,但您需要这样做才能与 HTML 绑定
猜你喜欢
  • 1970-01-01
  • 2016-12-21
  • 2017-04-14
  • 2015-10-08
  • 1970-01-01
  • 2019-04-19
相关资源
最近更新 更多