[英]POST new value using ng-change
I'm attempting to fire off a POST request upon selection of an option within my Angular app. 我试图在Angular应用中选择一个选项后触发POST请求。 Below is my current code.
下面是我当前的代码。
HTML: 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
Where does playerId
come from? playerId
来自哪里? It's not declared nor passed as a parameter to your changeMax
function. 它没有声明,也没有作为参数传递给
changeMax
函数。
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'}}
}
});
The issue was in my controller. 问题出在我的控制器上。 I was handling a POST request just like I handle GET requests which apparently does not work.
我正在处理POST请求,就像处理显然无法正常工作的GET请求一样。 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);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.