angularfire,对检索到的数据进行回调

angularfire, callback on retrieved data

本文关键字:数据 回调 检索 angularfire      更新时间:2023-09-26

我想在取回firebase数据后调用一个函数,但在ref对象上没有看到任何类似的promise函数。有什么建议吗?这是我的代码:

angular.module('myMod', ['firebase']).controller('myCtrl', ['$scope', '$firebase',
    function($scope, $firebase) {
        var ref = new Firebase('myfirebaseurl');
        $scope.data = $firebase(ref);
        // i want to do something like
        data.then(function(){
           someFunc();
        });
        // or something like
        $scope.$watch('data', function(){
            if($scope.data.desiredProperty) {
              doSomething();
            }
        });
    }]);

我在尝试使用Angularfire做所有事情时浪费了相当大的时间,而实际上大多数Firebase功能在没有它的情况下更容易实现。

为了满足您的需求,我建议如下:

var ref = new Firebase('myfirebaseurl');  // get your ref
// Called once with the initial data and again every time the data changes
ref.on("value", function(data) {
  $scope.data = data.val();
  someFunc();
});

上面的代码满足了您的需要。当检索数据时,它将被调用一次,并且在数据更新时,它会被再次调用。如果你只想在第一次加载数据时调用它,你可以使用:

ref.once("value", function(data) { ... }); 
AngularFire为"已加载"answers"已更改"事件提供了事件处理程序。来自注释来源:
object.$on = function(type, callback) {
  switch (type) {
  case "change":
    self._onChange.push(callback);
    break;
  case "loaded":
    self._onLoaded.push(callback);
    break;
  default:
    throw new Error("Invalid event type " + type + " specified");
  }
};

所以你应该能够做这样的事情:

var ref = new Firebase('myfirebaseurl');
$scope.data = $firebase(ref);
$scope.data.$on('loaded', function(){
    if($scope.data.desiredProperty) {
      doSomething();
    }
});

编辑:

看起来AngularFire loaded事件触发时,$scope.data对象尚未完全填充。这似乎是一个已知的问题,但有一些方法可以解决它

将数据作为参数访问loaded回调函数:

$scope.data.$on("loaded", function(data) {
  console.log(data);
}

完全跳过AngularFire并直接命中Firebase API:

ref.on("value", function(data) {
  console.log(data.val());
}

您需要使用$loaded和$watch promise的组合来处理从Firebase返回的数据。有关更多信息,请查看AngularFire文档。

如果您的数据是一个对象,请尝试以下代码。观察集合中的变化有点不同,但基本上是一样的。

angular.module('myMod', ['firebase'])
  .controller('myCtrl', ['$scope', '$firebase', function ($scope, $firebase) {
    var data = $firebase(new Firebase(URL));
    //to take an action after the data loads, use the $loaded() promise
    data.$loaded.then(function () {
        console.log("loaded record:", data.$id, data.otherData);
        someFunc();
    //Register an event listener which will be notified any time there is a change to the data.
        data.$watch(function (event) {
            console.log(event);
            if (data.desiredProperty) {
                doSomething();
            }
        });
    });
    //For three-way data bindings, bind it to the scope instead
    data.$bindTo($scope, "data");
}]);

我通常最终会使用一些AngularFire绑定,并将其与核心Firebase SDK提供的方法混合使用。