nested parameters in angular query
Asked Answered
S

1

8

I have a basic angular resource (angular 1.0.7):

app.factory "User", [ "$resource", ($resource)->
  $resource "/users/:id", { id: '@id' }, {
    index:     { method: 'GET', isArray: false }
  }
]

I can pass parameters like:

User.index({ foo: 1, bar: 2 })

But I need to pass nested parameters:

User.index({ foo: { bar: 1 } })

And this fails because it sends:

/users?foo=%5Bobject+Object%5D

I tried:

User.index({ foo: JSON.stringify({ bar: 1 }) })

But obviously parameters are not recognised on the server side (mere strings) and I'd like to avoid the hassle of parsing there.

Do you have an elegant solution to this issue?


With jQuery I'd have done:

$.get("/users", { foo: { bar: 1 } } )

Producing:

/users?foo%5Bbar%5D=1

Perfectly interpreted by the server.


Seems like a known issue (here too), let's stick to an ugly patch from now...

Swinge answered 3/9, 2013 at 9:24 Comment(6)
Why do you want to pass nested parameters?Bung
Are you really asking me why I'm asking my question?Swinge
I am just asking why a nested object is required for GET operation :) I can understand it for POSTBung
oh ok :) because I've complex and nested search query to get passed to elasticsearchSwinge
As the url templating works, It looks for properties on the object to bind to template placeholders and rest it adds to querystring, so i am not sure if it can be done. Give an example of a GET url which takes such nested parameter.Bung
added example in the questionSwinge
N
3

Not as elegant as the changes coming to Angular but you should be able to solve this by setting your param with the results of a function:

User.index.get({ "foo": (function () { 
    return JSON.stringify({ bar: 1 });
})() } );

Results in a HTTP request similar to what you were looking for:

?foo=%7B%22bar%22:1%7D

The entire angular example:

var app = angular.module('myApp', ['ngResource']);
var restUrl = window.location + 'echo/json/';

app.factory('User', function($resource, $http){
    return {
        index: $resource(restUrl)
    }               
});

function RestCtrl($scope, User) {
    $scope.url = restUrl;
    User.index.get({ "foo": (function () { 
        return JSON.stringify({ bar: 1 });
    })() } );
}

http://jsfiddle.net/pherris/U8F8G/6/

Nod answered 25/9, 2013 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.