【问题标题】:AngularJs $http post request to send data to rails controllerAngularJs $http post请求将数据发送到rails控制器
【发布时间】:2016-08-21 18:10:05
【问题描述】:

我正在研究 rails mvc,并且我正在使用 angularjs(对它来说很新)来处理各种 javascript 函数。我有一些 id 的数组,我想通过 $http post 方法发送到相应的 rails 控制器的 create 方法。

我的服务是:

.service('teamService' , function ($http) {
  var TeamService = {};
  TeamService.saveTeam = function(player_ids) {
  $http.post('/user_teams',player_ids)
  .success(function(data,status){
    data = player_ids;
    status =  true;
});
};

对应的角度控制器函数为:

    $scope.saveTeam = function () {
  var mf = $scope.getIDs($scope.Midfielders.data);
  var df = $scope.getIDs($scope.Defenders.data);
  var fw = $scope.getIDs($scope.Forward.data);
  var gk = $scope.getIDs($scope.GoalKeeper.data);
  var player_ids = mf.concat(df,fw,gk);
  teamService.saveTeam(player_ids);
};

当我在调用控制器 saveTeam 函数的视图中单击按钮时,它会在控制台中显示错误 422 无法处理的条目。我做错了什么?

【问题讨论】:

  • 你走错了路。阅读$http$q 和承诺的文档,然后继续你的工作。

标签: ruby-on-rails angularjs http post


【解决方案1】:

根据错误消息,我相信您的发布请求会发送到您的 Rails 控制器,但这就是发生错误的地方。

Angular 方面的一项调整可以帮助进行故障排除,并且通常一个好的做法是处理 http 调用的错误情况的函数。

所以不是

$http.post('/user_teams',player_ids)
  .success(function(data,status){
    data = player_ids;
    status =  true;
});

也许可以试试:

$http.post('/user_teams',player_ids)
  .then(function(data,status){
    data = player_ids;
    status =  true;
},function(error){
     //handle what happens if there is an error with the http post call
     console.log("Error occurred: " + error);
});

.then()的第一个函数是处理你的http调用成功的函数,第二个函数只有在http调用发生错误时才会被调用。

关于 Angular 的 $http 的附加信息:https://docs.angularjs.org/api/ng/service/$http#

希望这会有所帮助, 悬崖

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多