【问题标题】:AngularJS $resource query returns array with a function in it, which is not does not fit well when iterating through dataAngularJS $resource 查询返回包含函数的数组,在迭代数据时不适合
【发布时间】:2014-04-09 16:14:25
【问题描述】:

我已将自定义 Array.prototype.functionName 添加到我的 js 文件中。我正在使用 AngularJS 1.2.3 当我调用 $resource 来返回查询时,它会将该自定义函数附加到响应数组中。当我遍历响应数组时,它会在解析自定义函数时返回异常,这就是我所相信的。谁能建议我如何解决这个问题

Array.prototype.functionName = function(){
    //sorting
}

我在我的服务中这样调用我的 $resource

return $resource('/url',{},{
    'List':{
         method: 'GET',
         isArray: true
    }
});

并在我的控制器中调用它

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
    }
});

【问题讨论】:

  • 不确定您是否完全了解资源的工作原理。您可以更新帖子以显示您要调用的网址吗?
  • 您需要将崩溃的代码提供给我们,因为我刚刚成功测试了您的示例。 plnkr.co/edit/HwSBYEo8xfPiH2WC8QWP
  • 在我的 $promise.then 函数中,我迭代了从 Django rest 框架获得的响应数据,看起来像 [b,b,b,b,...,$promise,$已解决,函数名称]。它呈现所有 b 对象,但在最后抛出异常并终止我的迭代。如果我注释掉 functionName 定义,它不会出现在 Data 中但仍然显示相同的异常
  • 你能更新上面的内容并展示你是如何迭代的吗? angular.forEach 和 array.forEach 都可以工作...
  • @Nix 我已经编辑过,我是如何迭代数据的,我想我应该尝试使用 angular.forEach

标签: javascript arrays angularjs


【解决方案1】:

您正在循环遍历数组的 properties([0],[1], length, $promise, etc) 与项目。

对于in 在这种情况下是不正确的,它说嘿我想遍历这个数组的每个属性,其中包括数组项,但它还包括其他一些 ng-resource`y 东西。

你应该使用angular.forEachData.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 调用执行完全相同的操作,它们访问了网址/Api 并期望返回一个数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多