I have defined myself an api for use with Angular.js:
angular.module('api', ['ngResource'])
.factory('Server', function ($resource) {
return $resource('http://localhost\\:3000/api/servers/:name');
})
.factory('ActiveServer', function ($resource) {
return $resource('http://localhost\\:3000/api/servers/active/:name', {},
{ start: {method: 'POST'}, stop: {method: 'DELETE'} });
});
The idea, is that I have a set of defined servers, available through the /api/servers/ uri. A particular server can be started by adding it to the /api/servers/active/ uri, and stopped by deleting it.
In my controller, I have the following code:
$scope.start = function() {
ActiveServer.start(this.server);
};
$scope.stop = function() {
ActiveServer.stop(this.server);
};
which again is triggered by buttons
<div class="well span4" ng-repeat="server in servers">
<h1>{{server.definition.name}}</h1>
<span class="label label-info">{{server.status}}</span>
<button type="button" class="btn btn-primary"
ng-click="start()">Start</button>
<button type="button" class="btn btn-primary"
ng-click="stop()">Stop</button>
</div>
Starting the server works alright, but I have trouble stopping it. The code above ends up with the following request:
Request URL:http://localhost:3000/api/servers/active?$$hashKey=005&_events=[object+Object]&definition=[object+Object]&status=ready
Request Method:DELETE
The definition-part of my server object, containing the name that identifies the server to stop, isn´t serialized right.
How can I fix this?
If your API (
ActiveServer) only needs to receive the server’s name to work, then pass only the server’s name during the service call. Like this:Passing the entire
this.serverobject in any service call will result on the entire object being parametrized into the HTTP request.extended explanation:
When you use something like
api/servers/:nameon your$resourceURL, you are basically saying that the:namepart will be replaced by the value of a property with the same name (in this case, ‘name’) received on the parameters (i.e.{name: 'someName'}).From the angularJS $resource documentation:
So, if you call
service.get({name: 'abc'})then URL of the request will beapi/server/abcIf you call
service.get({name: 'abc', id: '123'})then URL will beapi/server/abc?id=123In your case, the
this.serverObject looks something like this:Since AngularJS does not do in-depth parametrization,
_eventsanddefinitionsare shown as_events=[object+Object]&definition=[object+Object]on the URL.