Search code examples
angularjshttpangularjs-serviceangular-servicesangularjs-factory

Sending a Post request in Angular 1.x via factory


The post request url should be updated in the following format.

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

Solution

  • Signature of $http.post method is post(url, data, [config])

    Here config is optional

    As you want to pass data as query string on post request, so you have to set the params property on config object.

    Factory:

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