简体   繁体   中英

POST new value using ng-change

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

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'}}
      }

  });

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);
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM