【问题标题】:Firebase, Storing snapshot datas to an array variableFirebase,将快照数据存储到数组变量
【发布时间】:2016-11-27 04:54:30
【问题描述】:

我可以使用ref.child('user').on('child_added',function()) 将用户内部的内容存储到数组变量中吗?

这是我的例子,

$scope.samplearray = [];
ref.child('user').on("child_added", function(snapshot) {
  $scope.samplearray.name = snapshot.val().name;
  $scope.samplearray.age = snapshot.val().age;
});

然后使用该数组在我的 html 中使用 ng-repeat 显示它

【问题讨论】:

  • 我的回答有帮助吗?

标签: javascript angularjs firebase firebase-realtime-database


【解决方案1】:

Firebase 数据库中的子事件是异步触发的,这是 Angular 1.x 中开箱即用的问题。您要么需要在添加到数组后直接触发 $digest 循环,要么使用 AngularFire。 I recommend you use AngularFire.

Vanilla SDK 方法

function MyController($scope) {
  var ref = firebase.database.ref('items');
  var items = [];
  ref.on('child_added', function(snap) {
    $scope.$evalAsync(function() {
      var item = snap.val();
      // use a super private property to keep around the key
      item.__key = snap.key; 
      items.push(item);
    });
  });
}

AngularFire 方法

function MyController($scope, $firebaseArray) {
  var ref = firebase.database.ref('items');
  // Handles all child events: added, removed, changed, moved
  $scope.items = $firebaseArray(ref);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多