javascript - AngularJS $resource 查询返回其中包含一个函数的数组,这在遍历数据时不适合

标签 javascript arrays angularjs

我已将自定义 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 () {
    }
     ...

Plunkr for your example

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/

相关文章:

Javascript:将局部变量传递给动态创建的函数,该函数是另一个函数内的参数

javascript:选择具有正确内容的类(class)

javascript - 如何使用 JavaScript 将 "href"属性动态添加到链接?

ruby - 在 Ruby 数组中测试数据

javascript - AngularJS 不解析从指令动态加载的数据

javascript - Vuejs中对象元素调用函数

javascript - 给定两个数组,我如何遍历一个数组并插入第二个数组的重复元素?

c - C 代码中的指针问题

angularjs - 在 AngularJS 中将指令插入 HTML 中?

javascript - 在html代码中从angularjs重复特定数量的div标签