Angular:将curl转换为Angular $ http POST请求

时间:2014-07-24 03:19:14

标签: javascript ajax angularjs curl

我有这个卷曲线:

curl -X POST -H "content-type: application/json" -H "AUTH_TOKEN: vLC4grMuKbtbamJL3L6x" localhost:8080/v1/segments?appkey=c2439fb30a1cad03e9e02bd733ef2ad5 -d '{"segment" : {"segment_name" : "ャロットケーキが好き", "segment_type":"static"}}'

现在curl直接命中了API。保存并重定向回路由'返回区域后,我希望能够进行$ http POST。$ save((function(){':

'use strict';
angular.module('otherLevelsApp').controller('GeoRegionCreateCtrl', [
'$scope', '$location', 'GeoRegion', 'Hours', '$http', function($scope, $location, GeoRegion, Hours, $http) {
console.log('new region controller');
$scope.app_id = (/apps\/(\d+)/.exec($location.absUrl())[1]);
$scope.newGeoRegion = true;
$scope.geoRegionId = '';
$scope.hours = Hours;
console.log('$scope.hours', $scope.hours);
$scope.geoRegion = {
  app_id: $scope.app_id,
  geoRegion_id: '',
  latitude: 37.7879938,
  longitude: -122.40743739,
  name: '',
  address: '',
  radius: 500,
  customer_id: $scope.customer_id
};
_.delay((function() {
  return $scope.setupGoogleMap();
}), 500);
window.test_scope = $scope;
return $scope.updateOrAddGeoRegion = function() {
  var region;
  $scope.loading = true;
  console.log('creating new region with ', $scope);
  region = new GeoRegion($scope.geoRegion);
  console.log('region', region);
  return region.$save((function() {
    return $location.path("/");
  }), function(response) {
    if (response.data.errors) {
      $scope.errors = response.data.errors;
    } else {
      $scope.errors = {
        "Error": ["There was a problem connecting with the server. Please try again later."]
      };
    }
    return $scope.loading = false;
  });
};

} ]);

你知道如何在$ http POST中正确格式化吗?特别是,我是否需要将成功和错误重构为$ http代码? IE浏览器。成功重定向返回$ location.path(“/”)或...?

我想这是沿着这些方向发展的东西,但不确定如何完成它:

$http({
method: 'POST',
url: '',
data: '',
headers: {'Content-Type': 'application/JSON'}

});

虽然我在这里阅读Angular doc:https://docs.angularjs.org/api/ng/service/ $ http#post我仍然有点困惑如何用$ http帖子直接点击这个卷曲?

感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

你要求任何帮助,所以这里有一些。不确定我是否理解你想要做的事情,但是为了结束,你可以从

开始
$http({
        url: 'localhost:8080/v1/segments?appkey=c2439fb30a1cad03e9e02bd733ef2ad5',
        method: 'POST',
        data: {'segment' : {'segment_name' : 'ャロットケーキが好き', "segment_type":"static"}},
        headers: {'Content-Type': 'application/json', 'Auth_Token': 'vLC4grMuKbtbamJL3L6x'}
}).success(function (data, status, headers, config) {
            //handle success
            $location.path('/'); //maybe you want to do this  
}).error(function (data, status, headers, config) {
            //handle error
});