M
M
mletov2016-03-17 14:13:14
JavaScript
mletov, 2016-03-17 14:13:14

In what format to pass json to Angular?

Please help:
Understanding Angular, ng-table.
Here is a request

var Api = $resource("/data.txt", false);       
        this.tableParams = new NgTableParams({}, {
            getData: function (params) {
                return Api.get(params.url()).$promise.then(function (data) {
                    params.total(data.inlineCount); // recal. page nav controls
                    return data.results;
                });
            }
        });

Here is the json
[{ "name": "christian", "age": 21 }, { "name": "anthony", "age": 88 }, { "name": "gfgfgfgf", "age": 8 }]

Mistake
angular.js:12332 Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array (Request: GET /data.txt)

Googled, the error is known, but all advice boils down to setting isArray to false. I can't figure out why Angular even thinks I'm passing it an array and not a json object.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Ulanov, 2016-03-17
@antonsr98

because [] is an array and you have json in it

_
_ _, 2016-03-17
@AMar4enko

This is not a bug - that's how ngResource is designed.
It's easier for you to use $http.get if you don't need to communicate with REST. Here is an excerpt from the standard methods documentation:

A resource "class" object with methods for the default set of resource 
actions optionally extended with custom actions. 
The default set contains these actions:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

According to the REST GET specification, a GET request can be used to request entity data or get a list of it. $resource.get is supposed to be used just for the first option, and $resource.query for the second.
Therefore, in the first case, ngResource expects to receive a JSON object, and in the second, an array of objects.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question