Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $resource query returns array with a function in it, which is not does not fit well when iterating through data

I have added a custom Array.prototype.functionName to my js file. I am using AngularJS 1.2.3 and when I call $resource to return a query, it appends that custom function in the response array. when i iterate over the response array, it return exceptions when parsing the custom function, that is what i believe. Can anyone suggest me how to work around this problem

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

I call my $resource like this in my service

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

and call it in my 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
    }
});
like image 332
Savitoj Cheema Avatar asked Feb 02 '26 19:02

Savitoj Cheema


1 Answers

You are looping over the properties([0],[1], length, $promise, etc) of the array versus the items.

For in is not correct in this case that says hey I want to loop over every property of this array which includes the array items, but it also includes some other ng-resource`y things.

You should be using angular.forEach, Data.forEach, or go old school and use a for(i;i<Data.length;i++)

I can see you don't fully understand what ng-resource is returning; The response from the query/array looks like this:

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

    });    

});

I included the out of the box way to do REST List using the query. Your List call and my Query call are doing the exact same thing they are hitting the url /Api and are expecting an array to be returned.

like image 83
Nix Avatar answered Feb 05 '26 08:02

Nix