1

My REST server is returning the following from /blog:

["hello","yo"]

This is my entire angularjs app:

var myapp = new angular.module("myapp", ["ngResource"]);

myapp.controller("MainCtl", ["$scope", "$resource", function($scope, $resource){
    var Blog = $resource("/blog/:entry", {entry: '@entry'});
    $scope.entries = Blog.query();
}]);

When I put {{entries}} somewhere in the html, I see this: [{"0":"h","1":"e","2":"l","3":"l","4":"o"},{"0":"y","1":"o"}]

Somehow angular is misinterpreting this array of values. I also tried this with exactly the same results:

myapp.controller("MainCtl", ["$scope", "$resource", function($scope, $resource){
    var Blog = $resource("/blog/:entry", {entry: '@entry'}, {
        list: {
            url: "/blog",
            method: "GET",
            isArray: true,
            transformResponse: function(data, headers) {
                var h = ["hello","yo"];
                console.log(h);
                return h;
            }
        }
    });
    $scope.entries = Blog.list();
}]);

Interestingly, that console.log call prints the correct value.

Jake
  • 2,515
  • 5
  • 26
  • 41

1 Answers1

0

This is definitely a duplicate of One dimensional array of strings being parsed to 2d by angular resource

When using $resource, if isArray = false, the expected response is a JSON object:

{
   "foo" : "bar"
}

If isArray = true, the expected response is supposed to be a JSON array of objects:

[
    { "foo" : "bar" },
    { "faa" : "bah" }
]

You have three options in this situation:

  1. Use $http instead of $resource
  2. Use $http's transformResponse functionality (see http://docs.angularjs.org/api/ng.$http)
  3. If you have control over the API, you can change the structure the response you are sending. Depending on semantics, you could send an array of objects (use isArray=true), or an object containing an array (use isArray=false). Whichever makes more sense to you.
Community
  • 1
  • 1
JBCP
  • 13,109
  • 9
  • 73
  • 111