我已将自定义 Array.prototype.functionName 添加到我的 js 文件中。我正在使用 AngularJS 1.2.3 当我调用 $resource 返回查询时,它会将自定义函数附加到响应数组中。当我遍历响应数组时,它在解析自定义函数时返回异常,这就是我所相信的。谁能建议我如何解决这个问题
Array.prototype.functionName = function(){
//sorting
}
我在我的服务中这样调用我的 $resource
return $resource('/url',{},{
'List':{
method: 'GET',
isArray: true
}
});
并在我的 Controller 中调用它
returnResource.List().$promise.then(function(Data){
console.log(Data); //Data has my custom function append at the end
for(var i in Data){
//do something
}
});
最佳答案
您正在遍历 properties([0],[1], length, $promise, etc)
数组与项目的对比。
对于 in
在这种情况下是不正确的,说嘿我想遍历这个数组的每个属性,其中包括数组项,但它还包括一些其他 ng-resource`y 东西。
你应该使用 angular.forEach
, Data.forEach
, 或者去老派并使用 for(i;i<Data.length;i++)
我看得出你没有完全理解什么ng-resource
正在返回;来自查询/数组的响应如下所示:
sort me![Resource, Resource, $promise: Object, $resolved: true, ...]
0: Resource
id: "nix"
__proto__: Resource
1: Resource
id: "nix2"
__proto__: Resource
$promise: Object
$resolved: true
length: 2
__proto__: Array[0]
.. array funcs
forEach: function forEach() {
[native code]
}
functionName: function () {
}
...
Array.prototype.functionName = function(){
//sorting
console.log("what is this...?", this, this.length);
this.forEach(function(item){
console.log(item);
});
}
app.controller('TestCtrl', function($scope, $resource) {
$scope.resource = $resource('url.json',{},{
'List':{
method: 'GET',
isArray: true
}
});
$scope.resource.List().$promise.then(
function(data){
console.log("List", this);
data.functionName();
});
$scope.resource.query().$promise.then(
function(data){
console.log("query", this);
data.functionName();
});
});
我包括了开箱即用的方式来做 REST List
使用查询。你的List
调用我Query
调用正在做与点击 url 完全相同的事情 /Api
并期望返回一个数组。
关于javascript - AngularJS $resource 查询返回其中包含一个函数的数组,这在遍历数据时不适合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22968274/