How to resolve an additional url using ng-resource

Supporting APIs exist, for example:

  • /players - to get a list for all players
  • /players{/playerName} - to get information about a specific player

and I already have a function using ng-resource, for example:

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

Is it possible to reuse this function for a specific player, for example:

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

so i want ...

  • send a request for /players if I did not pass the name parameter.
  • send request /players/someone if I passed name parameter with someone

Otherwise, do I need to write another function for a specific game?

+4
source share
3 answers

Using ngResource is very, very simple (it is basically two-line). You do not even need to create any custom actions here *.

I posted a working Plunkr here (just open the 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 } 
+12
source

Here is how I did it. Thus, you do not need to write a custom resource function for each of your endpoints, you simply add it to the list of resources in the list. I defined a list of endpoints that I wanted to use as follows.

 var constants = { "serverAddress": "foobar.com/", "resources": { "Foo": { "endpoint": "foo" }, "Bar": { "endpoint": "bar" } } } 

Then resources are created from each of them, like this.

 var service = angular.module('app.services', ['ngResource']); var resourceObjects = constants.resources; for (var resourceName in resourceObjects) { if (resourceObjects.hasOwnProperty(resourceName)) { addResourceFactoryToService(service, resourceName, resourceObjects[resourceName].endpoint); } } function addResourceFactoryToService (service, resourceName, resourceEndpoint) { service.factory(resourceName, function($resource) { return $resource( constants.serverAddress + resourceEndpoint + '/:id', { id: '@id', }, { update: { method: 'PUT', params: {id: '@id'} }, } ); }); 

}

The best part is that it takes 2 seconds to add a new endpoint, and I even chose the put method for you. You can then embed any of your resources in your controllers like this.

 .controller('homeCtrl', function($scope, Foo, Bar) { $scope.foo = Foo.query(); $scope.bar = Bar.get({id:4}); } 
+4
source
  • Use Play.query () to find all players.
  • Use Play.get ({name: $ scope.name}) to find one player
-2
source

Source: https://habr.com/ru/post/1502813/


All Articles