通过工厂在 Angular 1.x 中发送 Post 请求

Sending a Post request in Angular 1.x via factory

post 请求 url 应按以下格式更新。

https://www.example.com/api/one-push?type=json&query=push&title=____&url=____&tag=___

<form ng-submit="submitUrl()">
 <input type="text" class="form-control block" ng-model="url.title" placeholder="title">
  <input type="text" class="form-control block" ng-model="url.urlString" placeholder="url">
  <input type="text" class="form-control block" ng-model="url.tag" placeholder="tag">
  <button>Add</button>
</form>

var app = angular.module('app', [])
.controller('searchController', ['$scope', '$http','searchService',   function($scope, $http,searchService) {
$scope.submitUrl = function() {
  $scope.url = {};
      searchService.updateUrl($scope.url).success(function(data) {
        $scope.url = data;
      })
  }
  }]);

app.factory('searchService',function($http) {
  var url = " https://www.example.com/api/one-push?";
  var Info = {};
  Info.updateUrl = function(url) {
    return $http.post(url, { 
          type: "json",
          url: url.title,
          urlString: url.urlString,
          tag: url.tag
    });
  }
  return Info;
});

您可以使用 "params" 实现此目的,如下所示。

app.factory('searchService',function($http) {
  var url = " https://www.example.com/api/one-push?";
  var Info = {};
  Info.updateUrl = function(url) {
    return $http.post(url, { 
          type: "json",
          params: {'type':'json','query':'push','title':title,'url':url,'tag':tag}
    });
  }
  return Info;
});

$http.post 方法的签名是 post(url, data, [config])

这里配置是可选的

因为您想在 post 请求中将数据作为查询字符串传递,所以您必须在配置对象上设置 params 属性。

工厂:

app.factory('searchService',function($http) {
    var url = " https://www.example.com/api/one-push";
    var Info = {};
    Info.updateUrl = function(url, data) {
       var _data = data || {};

       return $http.post(url, _data, { 
          responseType:  "json",

          // Pass the data you want to pass as query params on request
          params: {
               type: "json",
               url: _data.urlString,
               query: 'push',
               title: _data.title,
               tag: _data.tag
          }
       });
    }
    return Info;
});