angularfire,检索数据的回调

时间:2013-12-15 03:36:26

标签: javascript angularjs firebase angularfire

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

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

3 个答案:

答案 0 :(得分:2)

我浪费了相当多的时间来尝试使用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) { ... }); 

答案 1 :(得分:0)

AngularFire为“已加载”和“已更改”事件提供事件处理程序。来自annotated source

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

答案 2 :(得分:0)

您需要使用$ loaded和$ watch promises的组合来处理从Firebase返回的数据。有关其他信息,请查看AngularFire Documentation

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

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提供的方法混合使用。