Search code examples
javascriptangularjsservicerestangular

Restangular getList does not return anything


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??


Solution

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