Angularjs resourceProvider returns $ prom with data

The angular.js service is provided:

angular.module('mymodule').factory('Products', ['$resource',
    function($resource) {
        return $resource('/path/to/getProducts', {}, {
            find: {
                method: 'GET',
                isArray: false
            }
        });
    }
]);

      

In the controller, mymodule

I make a request find

:

$scope.findAll = function () {
    Products.find(function (products) {
        console.log(Object.keys(products));
        // ['prodA', 'prodB', ... , '$promise', '$resolved']
        for (var i in products) {
            if (!products.hasOwnProperty(i)) continue;
            console.log(products[i].description.someprop);
            // Got error: Cannot read property 'someprop' of undefined
            // Trust me: I debug this place. someprop is defined for all items except that two
        }
    });
};

      

It works fine, but it returns a $ promise and $ is resolved with the dataset, so I cannot loop through my data.

Angular documentations says Instances Resource

and Collection have these additional properties. But I don't understand exactly how to manage it in my code.

What am I doing wrong? How can this be prevented?

+3


source to share


4 answers


Indeed, it is a little more complicated when you are not working with arrays.

The object response

sent from the server contains:

  • object resource

    (your data + $promise

    and $resolved

    , what you get in your callback)
  • a config

    object (headers, method used, url, etc.) and headers

    function
  • and the data

    object we want! It only contains data.

But you can see response.resource

in yours then()

. Therefore, you need to intercept the response sent by the server to get the data:

return $resource('/path/to/getProducts', {}, {
        find: {
           method: 'GET',
           isArray: false,
           interceptor: {
             response: function(response) {  
               return response.data;
             }
           }
        }
    });

      



And then in your controller:

Products.find().$promise.then(
    function(products){
        angular.forEach(products, function(value, index){
            console.log(value);
        });
    }
);

      

Tell me if it works for you.

Demo version of the plunger

+8


source


Resources return a promise, you can retrieve data from a promise using then()

.



Products.find().$promise.then(function (products) {
    console.log(Object.keys(products));
});

      

0


source


I think your problem is isArray: false. This way your products are not an array but an object. Set 'isArray: true' and you can iterate over (var product in products) all day.

0


source


Try to execute response.toJSON and it only returns your json excluding promise and determination.

data.$promise.then(function(myResponse) {
    var actualData = myResponse.toJSON();
}

      

0


source







All Articles