gpt4 book ai didi

javascript - Restangular getList 不返回任何东西

转载 作者:行者123 更新时间:2023-11-30 12:24:14 24 4
gpt4 key购买 nike

我对 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 approach”,但我没有 $scope 到服务中,所以我不知道如何解决这个问题,

有什么想法吗??

最佳答案

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

Angular 工厂的常见做法是返回 promise 本身:

// 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!
});

关于javascript - Restangular getList 不返回任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30015267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com