通过工厂

时间:2016-09-22 12:03:22

标签: angularjs http angularjs-service angular-services angularjs-factory

邮寄请求网址应按以下格式更新。

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

2 个答案:

答案 0 :(得分:0)

您可以使用&#34; params&#34;实现这一点如下。

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

答案 1 :(得分:0)

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

此处配置是可选的

由于您希望在发布请求时将数据作为查询字符串传递,因此您必须在配置对象上设置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;
});