Angular 1.0.8 $resource with multiple optional get parameters

All we need is an easy explanation of the problem, so here it is.

My Student ulr looks like this:

var Student = $resource('/app/student/:studentid:courseId',
    {studentid:'@id',courseId:'@cid'}
);

When I call it without parameters I would like the url be /app/student/ (works)

var names=Student.query(
  function(){
      deferred.resolve(names);
  }
);

When I call it with studentid I would like the url be /app/student/?id=88 (works)

    Student.get({"id":id},
      function(data){
          deferred.resolve(data);
      }
    );

When I call with courseid only I would like the url be /app/student/?courseid=99 (doesnt)

    Student.query({courseId:cId},
      function(data){
          deferred.resolve(data);
      }
    );

Instead I get: /app/student/6682831673622528

When I call with both student and course id I would like: /app/student/?id=1&courseid=2
Instead I get /app/student/12

Trying something like this for the url: /app/student/:studentid&:courseid gives me /app/student/1&2

Somehow, only giving studentid works but courseid or both doesn’t work as I would want it. Not sure how I would expect it because there nothing in the documentation about multiple parameters as a query string (there is on extending the url with /app/student/studentid/1/courseid/2 but since it’s an xhr request I’d like to have it request /app/student/ with the GET parameters appended as ?one=val&two=val

Is there a way to do this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you need parameters to be mapped to the query parameters, not the path parameters, you shouldn’t put the name of parameters into the path. E.g. student resource should look like this:

var Student = $resource('/app/student/',
    {}
);

Then invocation like this will work without any problems:

 Student.get({id:12,courseId:55});//calls /app/student/?id=12&courseId=55
 Student.get({id:12});//calls /app/student/?id=12
 Student.get({courseId:55});//calls /app/student/?courseId=55

The others cases will work as well. Just don’t confuse path parameters with query parameters.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply