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?
source to share
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.) andheaders
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.
source to share