Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resolve optional url path using ng-resource

Tags:

rest

angularjs

There are restful APIs, for instance:

  • /players - to get list for all players
  • /players{/playerName} - to get info for specific player

and I already have a function using ng-resource like:

function Play() {
  return $resource('/players');
}

Can I reuse this function for specific player like:

function Play(name) {
  return $resource('/players/:name', {
    name: name
  });
}

so I want to...

  • send request for /players if I didn't pass name parameter.
  • send request for /players/someone if I passed name parameter with someone

Otherwise, I have to write another function for specific play?

like image 220
Outsider Avatar asked Dec 09 '22 12:12

Outsider


1 Answers

Using ngResource it's very, very simple (it's basically a two-liner). You don't need even need to create any custom actions here*.

I've posted a working Plunkr here (just open Chrome Developer tools and go to the Network tab to see the results).

Service body:

return $resource('/users/:id/:name', { id:'@id', name: '@name' })

Controller:

  function( $scope, Users ){
    Users.query(); // GET /users (expects an array)
    Users.get({id:2}); // GET /users/2
    Users.get({name:'Joe'}); // GET /users/Joe
  }
  • of course, you could, if you really wanted to :)
like image 137
Rafal Pastuszak Avatar answered Jan 10 '23 17:01

Rafal Pastuszak