The Problem:
I'm doing (what I think is but maybe isn't) a simple angular.forEach
over an array then using $resource
to make a call based on each value returned. The result of each call is an object, as I'm expecting. But, I can't get these objects to join harmoniously in the way the angular.forEach documentation demonstrates.
But first, some code that works and then a look at code that fails.
Works:
var uniqueIds = {};
angular.forEach(object, function(key, value){
this.push(key.uniqueIds);
}, uniqueIds);
console.log(uniqueIds)
// uniqueIds equals the expected array
Fails
Here's where things get tricky. Now, in the next sample, inside the angular.forEach
is a $resource
call.
angular.forEach(array, function(index){
Resource.query({id:index}, function(result){
console.log(result)
// returns the expected object,
// but, as expected, I can't access the object outside the async call
});
console.log(result);
// result is undefined
});
Given the async-ness, it seems a promise could solve the problem. But it doesn't--I'm really still inside the async call. Nor does assigning result
to $scope
work. In short, I can't seem to get a value outside the Resource.query
.
What Do I Need To Happen?
I need the returned object of each $resource
call to add up to one object (using angular.extend? I've tried that) in the same way the angular.forEach
created an array. I've tried many different approaches, most all based on answers for general async questions asked here, but so far to no avail. I'm positive it's an issue with getting the value out of the $resource
call, but how to do that in this case I'm a bit baffled.
Something like this?
var promises = [];
angular.forEach(array, function(index) {
promises.push(Resource.query(...));
});
$q.all(promises).then(function(result1, result2, result3 ...) {
// do stuff with result1, result2 ... or
// var results = Array.prototype.slice.call(arguments);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With