angular.forEach和对象 [英] angular.forEach and objects
问题描述
问题:
我在做(我认为是,但也许不是)一个简单的 angular.forEach
一个数组,然后使用 $资源
能够基于每个值的调用返回。每次调用的结果是一个对象,我期待。但是,我不能让这些对象在 angular.forEach文档演示的方式和谐地加入。
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.
但首先,一些code,它的工作原理,然后看看code失败。
But first, some code that works and then a look at code that fails.
作品
var uniqueIds = {};
angular.forEach(object, function(key, value){
this.push(key.uniqueIds);
}, uniqueIds);
console.log(uniqueIds)
// uniqueIds equals the expected array
失败
这就是事情变得棘手。现在,下一个样品中,在 angular.forEach
是 $资源
通话中。
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
});
由于异步的烦躁,似乎一个承诺可以解决这个问题。但doesn't - 我确实还是异步调用里面。也没有分配结果
到 $范围
的工作。总之,我似乎无法获得 Resource.query
之外的值。
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
.
我需要什么发生?
我需要每个 $资源返回的对象
来电加起来一个对象(使用angular.extend?我已经试过了)以同样的方式在 angular.forEach
创建一个数组。我尝试过许多不同的方法,最重要的是基于问这里一般异步问题的答案,但至今没有结果。我敢肯定它与所获得的价值了 $资源
电话,但怎么做,在这种情况下,我有点束手无策。
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.
推荐答案
这样呢?
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);
});
这篇关于angular.forEach和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!