Note that there are some explanatory texts on larger screens.

plurals
  1. POCan Angular $resource.get handle both array and non-array for GET?
    primarykey
    data
    text
    <p>There are two ways I can GET a REST resource by ID:</p> <pre><code>GET /users/1 GET /users/1,2 </code></pre> <p>The first returns a single object like <code>{id:1,name:"John"}</code> while the second returns an array like <code>[{id:1,name:"John"},{id:2,name:"Jill"}]</code>.</p> <p>Please, no arguments about whether or not this is legit REST; just accept that a service has this and I need to work with it.</p> <p>angular's $resource actually intelligently handles it from the <em>request</em> side:</p> <pre><code>User.get({users:['1','2']}) </code></pre> <p>transforms into</p> <pre><code>GET /users/1,2 </code></pre> <p>But it doesn't handle the response well. It expects a single object. If I change the definition to <code>isArray:true</code>, then it fails on a single request <code>GET /users/1</code></p> <p>How do I get it to intelligently handle both? </p> <p>EDIT: I did some weird hacking to get it to work, but would prefer a native method:</p> <pre><code> factory('Resource',['$resource','_',function ($resource,_) { return function(url,params,methods){ var defaults = { getSingle: {method: 'get', isArray:false}, getMultiple: {method: 'get', isArray:true} }, resource = $resource(url,params,angular.extend(defaults,methods)), urlParams = {}; _.each(url.split(/\W/), function(param){ if (param &amp;&amp; (new RegExp("(^|[^\\\\]):" + param + "\\W").test(url))) { urlParams[param] = true; } }); // do not override if they did if (!(methods||{}).get) { resource.get = function (params,success,error) { // look for multiples var isMultiple = false; _.each(params,function (val,key) { if (key &amp;&amp; urlParams[key] &amp;&amp; angular.isArray(val)) { isMultiple = true; return(false); } }); return this[isMultiple?"getMultiple":"getSingle"](params,success,error); }; } return(resource); }; }]). </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload