62

The following JSON response from the server

[
    "hello",
    "world"
]

is being parsed into a 2d array by this ngResource service

myService.factory('Name', function($resource){
    return $resource(site_url+'api/accounts/:accountId/names/', {}, {
        list: {method:'GET', params:{}, isArray:true}
    });
});

called like so

$scope.names = Name.list({accountId:$scope.account.id}, function(e){
    console.log(e);
});

traces to

[{"0":"h","1":"e","2":"l","3":"l","4":"o"},{"0":"w","1":"o","2":"r","3":"l","4":"d"}]

Any hints?

ricick
  • 5,694
  • 3
  • 25
  • 37

2 Answers2

99

TLDR; ngResource expects an object or an array of objects in your response.


When isArray is set to true in the list of actions, the ngResource module iterates over each item received in the response and it creates a new instance of a Resource. To do this Angular performs a deep copy between the item received and the Resource class, which gives us an object with special methods ($save, $delete and so on)

Check the source here.

Internally angular uses angular.copy to perform the deep copy and this function only operates with objects and arrays, when we pass a string, it will treat it like an object.

Strings in JS can behave as arrays by providing sequential access to each character. angular.copy will produce the following when passed a string

angular.copy('hi',{})   => {0:'h', 1:'i'}

Each character becomes a value in an object, with its index set as the key. ngResource will provide a resource with properties 0 and 1.


Your choices are:

Use the lower level $http service

$http.get('/res').success(function(data){
  $scope.test = data;
});

Return an array of objects in your json response

[{'data': "hello"}, {'data': "world"}] 

Intercept the response and change your data

If you cannot modify the data the server sends back and want to use ngResource you will need to transform the response. Read how to do it here

jaime
  • 41,961
  • 10
  • 82
  • 52
  • 3
    Thanks - if I only come across this earlier :) – dev_doctor Jul 18 '13 at 01:56
  • 3
    thanks, i spent 12 hours searching a solution. thanks to you i won't spend 25 hours :). I was returning a single object and isArray was set to false, however i still had the same problem. I fixed it by still using resource and putting it in a list from the server side as you suggested. – Adrian Hedley Oct 01 '13 at 09:18
  • `isArray: false` not working, you need to transform returned string to object check this solution [link](http://stackoverflow.com/questions/15725445/angularjs-resource-not-working-with-an-array-returned-from-a-rest-api/22491240#22491240) – Hisham Mar 31 '16 at 16:15
-1

I have been struggling with this as well. Here is my solution by adjusting the service slighly by using query

var app = angular.module('testApp', ['ngResource']);

app.factory('Name', function($resource, $sce) {
  var path = "test.json";

  return $resource(path, {}, {
    query: {
      method: 'GET',
      isArray: false
    }
  })
});

app.controller('testController', function($scope, Name) {
  $scope.result;

  $scope.getResult = function() {
    Name.query(function(data) {
      $scope.result = data;
    });
  };

  $scope.getResult();
});

HTML:

<!DOCTYPE html>
<html ng-app="testApp">

<head>

  <link href="style.css" rel="stylesheet" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>

  <script src="script.js"></script>
</head>

<body ng-controller="testController">
  <h1>{{result.surname}}</h1>

</body>

</html>

and the JSON file:

{
    "name": "Homer",
    "surname":  "Simpson",
    "Town": "Springfield"
}

and also working Plunker if interested: http://plnkr.co/edit/SwqlZyqZ4zfcpaLxaf39

Hope this help someone ...

vidriduch
  • 4,753
  • 8
  • 41
  • 63