简体   繁体   English

AngularJs $ http发布请求以将数据发送到Rails控制器

[英]AngularJs $http post request to send data to rails controller

I am working on rails mvc and I am using angularjs (quite new to it) for various javascript functions. 我正在使用Rails MVC,并且正在为各种JavaScript函数使用angularjs(非常新)。 I have an array of some ids that i want to send to my corresponding rails controller's create method via $http post method. 我有一些要通过$ http post方法发送到相应的rails控制器的create方法的ID数组。

My service is: 我的服务是:

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

The corresponding angular controller function is: 相应的角度控制器功能为:

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

when I click the button in views calling the controller saveTeam functions it says error 422 unprocessable entry in the console. 当我单击调用控制器saveTeam函数的视图中的按钮时,它说控制台中出现错误422无法处理的条目。 What am I doing wrong? 我究竟做错了什么?

Based on the error message, I believe your post request makes it to your Rails controller but that is where the error is occurring. 根据错误消息,我相信您的发布请求将其发送到Rails控制器,但这就是发生错误的地方。

One tweak on the Angular side that can help with troubleshooting, and often a good practice to have is a function to handle the error case for your http call. 可以对Angular进行的一项调整可以帮助进行故障排除,并且通常有一个好的作法是处理HTTP调用错误情况的功能。

So instead of 所以代替

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

Maybe try something like: 也许尝试类似:

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

The first function of the .then() is the function to handle a successful result from your http call, the second function will only be called if an error occurred for the http call. .then()的第一个函数是处理您的http调用成功结果的函数,仅当http调用发生错误时才调用第二个函数。

Additional info on Angular's $http: https://docs.angularjs.org/api/ng/service/ $http# 有关Angular的$ http的其他信息: https : //docs.angularjs.org/api/ng/service/ $ http#

Hope this helps, Cliff 希望这会有所帮助,Cliff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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