Angular:这是构造$ http POST请求的正确方法吗?

时间:2014-07-28 02:19:45

标签: javascript angularjs

我在这里有一个示例卷曲线,我试图改成$ http POST:

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"}}'

下面是Angular代码,你可以看到底部我有一个POST请求。我只想澄清我的格式是否正确或是否存在问题?我特别感兴趣的是知道我是否正确传入了segment_name($ scope.geoRegion.name)

   '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 $http({
          url: "http://localhost:8080/v1/segments?appkey=" + window.APP_KEY,
          method: "POST",
          data: {
            segment: {
              segment_name: $scope.geoRegion.name,
              segment_type: "static",
              filter: null,
              estimate: null,
              estimated_at: null
            }
          },
          headers: {
            "Content-Type": "application/json",
            Auth_Token: window.AUTH_TOKEN
          }
        }).success(function(data, status, headers, config) {
          return $location.path("/");
        }).error(function(data, status, headers, config) {
          return $scope.errors = {
            "Error": ["There was a problem creating your Geo Segment. Please try again later."]
          };
        });
      }), 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;
      });
    };
  }
]);

1 个答案:

答案 0 :(得分:1)

  

我特别感兴趣的是知道我是否正确传入了segment_name($ scope.geoRegion.name)