简体   繁体   中英

Cleanest way to POST using a service in Angular?

Right now I have a post method that works fine in a controller but what's the best way to refactor this into a service? Most importantly, I need to be able to pass $scope.tag from ng-model in the post. Then the post makes a call to the server for an external API request using the post params in the url.

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

Refactor request method to a factory service and put request logic in there. ie. SearchService

So, inject SearchService in MainController and access the service request method that returns a promise.

Example:

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

    $scope.submit = function () {

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

    }
  }
]);

Have a look at some of the style guides and best practices by the community, recommended JohnPapa's Styleguide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM