Angular 1.0.8 $resource with multiple optional get

2019-03-11 03:39发布

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?

1条回答
手持菜刀,她持情操
2楼-- · 2019-03-11 04:00

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.

查看更多
登录 后发表回答