Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs $resource - cannot pass array as one of the parameters

I am trying to pass an array to our API from AngularJS. However when sent, the parameters are repeated instead of sent as an array. Here is my code:

    angular.module('sigApp.services', ['ngResource']).
    // Fetch cases from server
    service('caseFetcher', ['$resource', function($resource) {
        this.getCases = function(params) {
            console.log('params: ',params);
            return $resource('/v1/cases/', params);
        };
    }]);

Here is the URL (abbreviated) that is generated: /v1/cases?status=OPEN&status=HELD

Here is the URL I want: /v1/cases?status%5B0%5D=OPEN&status%5B1%5D=HELD (aka ?status[0]=OPEN&status1=HELD )

Here is the screenshot for the object that is logged in the code above: enter image description here

I have tried the latest version of angularjs (1.2rc1) and also tried the Restangular plugin. No matter what I try I get the params passed multiple times, rather than in array format. Our API can't work with multiple values with the same key.

Any ideas?

EDIT: Several people have marked this as duplicate when the other question (AngularJS: ngResource and array of object as params to URL) is not like this at all. The other question deals with sending an array via POST and I am trying to do a GET request (which set to isArray: true by default) and I want to pass only one of the parameters an array as, which that answer does not seem to help me to. So can someone please help with this?

Update I answered my own question below but as commented I am giving more information for any who come across this problem. We are using the Play Framework 2.1 for our backend. I was not able to generate the numbered array I originally posted above but was able to get it to work just an a non-indexed array so this is the URL that was generated that eventually worked:

/v1/cases?status%5B%5D=OPEN&status%5B%5D=HELD (aka ?status[]=OPEN&status[]=HELD )

Hope this helps someone else

like image 358
Scotty Bollinger Avatar asked Aug 19 '13 16:08

Scotty Bollinger


1 Answers

I solved my own issue by changing how the params were set that were passed to $resource. Instead of:

$scope.params.status = ['OPEN','HELD'];

I used:

$scope.params["status[]"] = ['OPEN','HELD'];

This allowed me to retrieve the values on the server as desired.

like image 183
Scotty Bollinger Avatar answered Oct 22 '22 14:10

Scotty Bollinger