问题:
我正在做(我认为是但也许不是)一个简单的angular.forEach
在数组上然后使用$resource
根据返回的每个值进行调用。正如我所期望的,每次调用的结果都是一个对象。但是,我无法让这些对象以angular.forEach 文档 http://docs.angularjs.org/api/angular.forEach演示。
但首先,查看一些有效的代码,然后查看失败的代码。
Works:
var uniqueIds = {};
angular.forEach(object, function(key, value){
this.push(key.uniqueIds);
}, uniqueIds);
console.log(uniqueIds)
// uniqueIds equals the expected array
Fails
这就是事情变得棘手的地方。现在,在下一个示例中,在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
});
考虑到异步性,承诺似乎可以解决问题。但事实并非如此——我实际上仍在异步调用中。也不分配result
to $scope
工作。简而言之,我似乎无法获得除此之外的值Resource.query
.
我需要做什么?
我需要每个返回的对象$resource
调用以相同的方式添加一个对象(使用 angular.extend?我已经尝试过)angular.forEach
创建了一个数组。我尝试了许多不同的方法,大多数都基于此处提出的一般异步问题的答案,但到目前为止没有任何效果。我确信这是一个获取价值的问题$resource
打电话,但在这种情况下如何做到这一点我有点困惑。