I'm attempting to fire off a POST request upon selection of an option within my Angular app. Below is my current code.
HTML:
<select ng-options="option for option in linked.maxOptions" ng-model="linked.selectedMax" ng-change="linked.changeMax()"></select>
Controller:
var playerId = $routeParams.playerId;
vm.changeMax = function() {
playersService.setMaxPoints({
playerId: playerId,
max: vm.selectedMax
}).$promise.then(function(res){
return res.success;
}, function(res) {
alert('Couldn\'t update number of points to ' + vm.selectedMax + ':' + res.success);
});
};
Service:
angular.module('gameApp')
.factory('playersService', ['$resource',
function($resource) {
var base = '/api/players/:playerId/';
return $resource(base, {}, {
setMaxPoints: {method: 'POST', url: base + 'maxPoints/' + ':max'}
});
}]);
The problem is that my parameters are not being passed to my service method for some reason as it attempts to hit this endpoint:
http://localhost:3010/api/players/maxPoints
答案 0 :(得分:1)
Where does playerId
come from? It's not declared nor passed as a parameter to your changeMax
function.
Here is how I declare resources. The syntax is a bit easier than yours so it's less error prone:
angular.module('myApp')
.factory('ActivityData', function($resource) {
return $resource('/service/data/:userEmail/:dataType', {dataType: 'all'},
{
getTotals: {method:'GET', cache: true, params: { dataType: 'total'}}
}
});
答案 1 :(得分:0)
The issue was in my controller. I was handling a POST request just like I handle GET requests which apparently does not work. I needed to pass a second, in this case empty, object to my service method call to get things working. I believe this is where you would pass any 'body' of data to your service call:
vm.changeMax = function() {
playersService.setMaxPoints({
playerId: playerId,
max: vm.selectedMax
}, {}).$promise.then(function(res){
return res.success;
}, function(res) {
alert('Couldn\'t update number of points to ' + vm.selectedMax + ':' + res.success);
});
};