Reputation: 253
I am really new with angular and restangular, maybe you can help me,
Why does this code work
tunariAppApp.controller('ProductListCtrl',
function ($scope, Restangular){
Restangular.all('products').getList().then(function(result){
$scope.products= result;
});
}
);
and this one doesnt????
tunariAppApp.controller('ProductListCtrl',
function ($scope, Restangular){
$scope.products = Restangular.all('products').getList();
});
I would like to migrate this code to a service, something like this:
tunariAppApp.factory('productData', ['Restangular', function(Restangular){
var Product = Restangular.all('products');
var allProducts = Product.getList();
return{
products: allProducts
};
}]);
but since Restangular.all('products').getList() does not return anything I can achive that. I could use the "then approach" but I don't have an $scope into a service so I cannot figure out how to resolve that,
any ideas??
Upvotes: 1
Views: 950
Reputation: 96
You could also use Restangular.all('products').getList().$object, this returns an array that when data arrives is populated. You can also bind to this array in views, etc, and they will be updated when data becomes available.
Upvotes: 0
Reputation: 5736
getList()
does not return data, it returns a promise object for the http request since requests are fetched asynchronously in order to not block js execution.
A common practice for angular factories is to return the promise itself:
// 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!
});
Upvotes: 3