首页 文章

AngularFire V1.2 $ firebaseArray()$ loaded()只调用一次[复制]

提问于
浏览
1

这个问题在这里已有答案:

我在数组上使用AngularFire和promise( $loaded()firebaseArray() 上) .

目前,我正在使用以下代码:

Problem :我转到第1页,数据加载完全正常 . 转到第2页并返回第1页 . 现在 $loaded() 在我进行整页刷新之前不起作用 . 我该如何解决这个问题?

app.factory('Items', ['FBURL', '$firebaseArray', function(FBURL, $firebaseArray) {
    return {
      ofCategory: function(catId){
        var ref = new Firebase(FBURL);
        var refSearch = new Firebase.util.NormalizedCollection(...).select(...).ref(); 
        var allItems= refSearch.orderByChild(...);
        return $firebaseArray(allItems);
      }
    }; 
}]);

第1页:

function readData() { 
  if($scope.Items) { 
     $scope.Items.$destroy();
     $scope.Items= null;
  }   
  $scope.Items = Items.ofCategory($routeParams.id);
  $scope.Items.$loaded().then(function(itm) {
        ...
  });
}

第2页:

$scope.Items= Items.ofCategory($routeParams.id);

Firebase文档1说:“ $loaded() 返回一个承诺,该承诺在从我们的数据库下载初始记录后解析 . 这是 only called once 并且应该小心使用”,这可能就是我在这里得到的 .

What I've tried :如图所示,在Page1上的 readData() 函数中,我在任何新加载之前销毁 $scope.Items 变量 . 但它似乎没有做任何事情 . AFAIU, $loaded() 正在 firebaseArray() 上工作,因此销毁 $scope 数组可能没有多大帮助 . 那么,我还需要做些什么来使这项工作无需完全刷新页面?

1 回答

  • 1

    我听说应该避免使用AngularFire,这看起来是一个很好的理由 .

    直接使用firebase API:

    app.factory('FbItems', ['FBURL', '$q', function(FBURL, $q) {
        return {
          ofCategory: function(catId){
            var ref = new Firebase(FBURL);
            var refSearch = new Firebase.util.NormalizedCollection(...).select(...).ref(); 
            var allItems= refSearch.orderByChild(...);
            var promise = allItems.once('value').then(function(snapshot) {
                return snapshot.val();
            });
            return $q.when(promise);
          }
        }; 
    }]);
    

    使用$q.when将ES6承诺转换为AngularJS $ q承诺非常重要 . 只有在AngularJS执行上下文中应用的操作才能受益于AngularJS数据绑定,异常处理,属性监视等 .

    用法:

    function readData() { 
      promise = FbItems.ofCategory($routeParams.id);
      promise.then(function(items) {
          $scope.Items = items;
      }).catch(function(error) {
          console.log(error);
      });
    }
    

相关问题