【问题标题】:Restangular getList does not return anythingRestangular getList 不返回任何内容
【发布时间】:2016-02-24 22:59:37
【问题描述】:

我是 angular 和 restangular 的新手,也许你可以帮助我,

为什么这段代码有效

tunariAppApp.controller('ProductListCtrl',
    function ($scope, Restangular){
    
    Restangular.all('products').getList().then(function(result){
        $scope.products= result;
    });
    }
);

而这个没有????

tunariAppApp.controller('ProductListCtrl',
    function ($scope, Restangular){
    
    $scope.products = Restangular.all('products').getList();
    });

我想将此代码迁移到服务中,如下所示:

tunariAppApp.factory('productData', ['Restangular', function(Restangular){
    
    var Product = Restangular.all('products');
    var allProducts = Product.getList();
    return{
        products: allProducts
        
    };
}]);

但是由于 Restangular.all('products').getList() 没有返回任何我可以实现的东西。我可以使用“then 方法”,但我没有 $scope 到服务中,所以我不知道如何解决这个问题,

有什么想法吗??

【问题讨论】:

  • 如果您找到满意的答案请标记答案

标签: javascript angularjs service restangular


【解决方案1】:

getList() 不返回数据,它为 http 请求返回一个 promise 对象,因为请求是异步获取的,以免阻塞 js 执行。

角度工厂的一个常见做法是返回承诺本身:

// fire restangular api call and return promise in factory
tunariAppApp.factory('productData', ['Restangular', function(Restangular){
    var Product = Restangular.all('products');
    return{
        products: function() { return Product.getList(); }
    };
}]);


// Deal with promise in controller (or anywhere else)
var allProducts = productData.products().then(function(result){
  // now you have results from restangular!
});

【讨论】:

    【解决方案2】:

    您也可以使用 Restangular.all('products').getList().$object,这将返回一个数组,当数据到达时填充该数组。您也可以在视图等中绑定到这个数组,当数据可用时它们将被更新。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2019-04-06
      • 2012-02-15
      • 2020-09-07
      • 2021-11-22
      • 2015-11-06
      相关资源
      最近更新 更多