在Angular中使用服务进行POST的最简洁方法?

时间:2015-11-15 06:47:45

标签: javascript angularjs api http

现在我有一个在控制器中工作正常的post方法但是将它重构为服务的最佳方法是什么?最重要的是,我需要能够在帖子中传递来自ng-model的$ scope.tag。然后帖子使用url中的post params调用服务器以获取外部API请求。

// controller
app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {

  $scope.submit = function () {
    var recipe = $scope.tag;
    $http.post('/api', {tag: recipe})
      .then(function(response) {
        $scope.recipeData = JSON.parse(response.data);
        console.log(response.data);
      });
  };

// server.js
app.post('/api', function (req, res) {
  var recipe = req.body.tag;
  request("http://externalapi.com/api/search?key=xxx=" + recipe, function (error, response, body) {
    res.json(body);
  });
});

// index.html
    <form class="form-inline" ng-submit="submit()">
      <div class="form-group">
        <input type="text" ng-model="tag" class="form-control">
        <button type="submit" value="Search" class="btn btn-default search-button"> Search</button>
      </div>
    </form>


---------refactored code----------


app.factory('searchFactory', ['$http', function ($http) {
    var obj = {};
    obj.fetchRecipes = function () {
      return $http.post("/api", { tag: "chicken" });
    };
    return obj;
}]);

app.controller('MainController', ['$scope', 'searchFactory', function ($scope, searchFactory) {
    $scope.submit = function () {
      searchFactory.fetchRecipes()
        .success(function(response) {
          $scope.recipeResults = response;
      });
    };
}]);

1 个答案:

答案 0 :(得分:0)

将请求方法重构为factory service并将请求逻辑放入其中。即。 SearchService

因此,在MainController中注入SearchService并访问返回promise的服务请求方法。

示例:

app.controller('MainCtrl', ['$scope', 'SearchService', 
  function ($scope, SearchService) {

    $scope.submit = function () {

       var promise = SearchService.getRecipe( $scope.tag );
       ..

    }
  }
]);

查看社区的一些风格指南和最佳做法,建议JohnPapa's Styleguide