How to get an array of numbers from angular.js resource?

my RESTful API returns an array:

GET /test => [1367297123312,1.0,2.0,3.0,100]

I have a service:

(angular
 .module('app.services', ['ng', 'ngResource'])
 .factory('myData', [
     /******/ '$resource',
     function ($resource) {
         return $resource('test');
     }])
);

In my controller I need to get numbers. I tried:

(angular
 .module('app.controllers', ['ng', 'app.services'])
 .controller('tweetsapiContr', [
     /******/ '$scope', 'myData',
     function ($scope,   myData) {
         myData.get({}, function (data) {
             console.log(data);
         };
     }
 ])
);

The above gives me an error TypeError: Object #<h> has no method 'push', and if I use queryinstead getin the service, it returns an array of objects with methods such as $get, $saveetc., but the call $get, for example, returns undefined.

How to get numbers? The answer with the hash from the server works, but I'm trying to figure out how to make it work with arrays.

+5
source share
4 answers

(# 4314) , ( , ) $resource.

, , $resource , (get, query, post ..). , , "" , $http.

, REST api.

+7

"" > actions. :

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

, :

:

$resource("/url/:someParam", {}, {
    getMyArray: {method:"GET", params: {someParam:"hello"}, isArray: true}
});

query, isArray: true, .

, GET , .

: JSON? " JSON " ?

+8

isArray: true; (docs)

return $resource('test', {}, {
  getArray: { method: 'GET', isArray: true } 
};

Then I think you should call it a dollar sign myData.$getArray

+5
source

You should not return JSON arrays, as they are vulnerable to cross-site attacks. Read this article why the part of http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

Returns an object with an array attached to the property. This will reduce potential attacks and solve your problem in one go.

{
    d: [1,2,3,4,5]
}


myData.get({}, function (data) {
    console.log(data.d);
};

Still want an array?

You can restructure the actions of the resource and set the isArray property to act on true.

Angular ngResource docs

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

$resource(url[, paramDefaults][, actions]);
+2
source

All Articles