【问题标题】:Sending a Post request in Angular 1.x via factory通过工厂在 Angular 1.x 中发送 Post 请求
【发布时间】:2017-01-31 00:03:07
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用“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;
    });
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 感谢您的回答。另一个更正用 _data 替换了 url,它起作用了 params: { type: "json", url: _data.urlString, query: 'push', title: _data.title, tag:_data.tag }
      猜你喜欢
      • 2018-09-11
      • 1970-01-01
      • 2018-05-04
      • 2011-06-10
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      相关资源
      最近更新 更多