如何在$ resource POST上设置请求体和参数

时间:2015-07-22 17:58:26

标签: javascript angularjs http

我正在尝试将请求正文中的数据和请求参数传递给Angular $资源调用。下面是我的控制器点击处理程序和它调用的服务:

controller.js:

vm.setLimit = function(limit) {
  var data = {
    activity: 'point_limit',
    limit: limit
  };
  playersService.setPlayerLimit({
    playerId: playerId,
    data
  });
};

service.js:

angular.module('gameApp')
  .factory('playersService', ['$resource',
    function($resource) {
      var base = '/api/players/:playerId/';
      return $resource(base, {}, {
        getPlayerInfo: {method: 'GET', url: base + 'playerInfo'},
        setPlayerLimit: {method: 'POST', url: base + 'playerLimit'}
      });
    }]);

getPlayerInfo有效,但setPlayerLimit不起作用,因为出于某种原因,它没有通过playerId

2 个答案:

答案 0 :(得分:5)

playersService.setPlayerLimit应按顺序采用4个参数:

(请求参数,请求正文,成功回调,错误回调)

将您的代码修改为:

playersService.setPlayerLimit({playerId: playerId}, data, success, error);

答案 1 :(得分:0)

找到解决方案here

'使用重载的method(params, payload)签名',如下所示:

vm.setPlayerLimit = function(limit) {
  playersService.setPlayerLimit({playerId: playerId}, {activity: 'point_limit', limit: limit});
};