给出angular.js服务:
angular.module('mymodule').factory('Products', ['$resource',
function($resource) {
return $resource('/path/to/getProducts', {}, {
find: {
method: 'GET',
isArray: false
}
});
}
]);
在mymodule
的控制器中,我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
}
});
};
它工作正常,但返回$ promise和$使用数据集解析,因此我无法遍历我的数据。
Angular文档says Resource
实例和集合具有这些附加属性。但我不明白如何在我的代码中控制它。
我做错了什么?怎么预防呢?
答案 0 :(得分:8)
当你不使用数组时,确实有点复杂。
从服务器发回的response
对象包含:
resource
对象(您的数据+ $promise
和$resolved
,这是您在回调中获得的内容)config
对象(标题,使用的方法,调用的网址等)和headers
函数data
对象,这就是我们想要的!它只包含数据。但您只能在response.resource
中看到then()
。因此,您需要拦截服务器发送的响应以获取数据:
return $resource('/path/to/getProducts', {}, {
find: {
method: 'GET',
isArray: false,
interceptor: {
response: function(response) {
return response.data;
}
}
}
});
然后在你的控制器中:
Products.find().$promise.then(
function(products){
angular.forEach(products, function(value, index){
console.log(value);
});
}
);
告诉我这是否适合你。
答案 1 :(得分:0)
资源返回一个promise,您可以使用then()
从承诺中检索数据。
Products.find().$promise.then(function (products) {
console.log(Object.keys(products));
});
答案 2 :(得分:0)
我猜你的问题是'isArray:false'。所以你的产品不是数组,而是对象。设置'isArray:true',您可以整天迭代(产品中的var产品)。
答案 3 :(得分:0)
尝试执行response.toJSON,它只返回你的json,不包括promise和resolve。
data.$promise.then(function(myResponse) {
var actualData = myResponse.toJSON();
}