Angular: centralized resource factory with promises

Let's say I have a resource that looks like this:

angular.module('productsModule').factory('productFactory', function($resource) {
    return $resource('/products/:id',{},
    {'query': {method: 'GET', isArray: false }});
});

      

And now I can use this in my controller like this:

productFactory.query().$promise.then(function(products) {
    // success
    console.log(products);
    $scope.products = products;
});

      

However, I would like to move this functionality into a factory so that I can do it on any controller and it will get a list of products, supporting promises:

$scope.products = productFactory.products 

      

This way I could have a reusable centralized resource. How can I achieve this in Angular?

+3


source to share


2 answers


You can actually do it with ngResource, while native promises don't unpack anymore, you can simply do:

 $scope.products = productFactory.query();

      



This is because executing .query

on ngResource returns an empty array, which will be automatically populated when the request is returned to the client and triggers the digest.

+1


source


angular.module('productsModule').factory('productFactory', function($resource) {
    var res = $resource('/products/:id',{},
               {'query': {method: 'GET', isArray: false }});
    var fn = function ($scope, prop) {
        res.query().$promise.then(function (products) {
            $scope[prop] = products;
        }
    }

    return fn;
});

      

In the controller:



productFactory($scope, 'products');

      

0


source







All Articles