简体   繁体   中英

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. I have an array of some ids that i want to send to my corresponding rails controller's create method via $http post method.

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. 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.

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.

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.

Additional info on Angular's $http: https://docs.angularjs.org/api/ng/service/ $http#

Hope this helps, Cliff

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