Javascript 在Angular中使用服务发布最干净的方式?
现在我有一个post方法可以在控制器中正常工作,但将其重构为服务的最佳方法是什么?最重要的是,我需要能够在文章中从ng模型传递$scope.tag。然后post使用url中的post参数向服务器发出外部API请求的调用Javascript 在Angular中使用服务发布最干净的方式?,javascript,angularjs,api,http,Javascript,Angularjs,Api,Http,现在我有一个post方法可以在控制器中正常工作,但将其重构为服务的最佳方法是什么?最重要的是,我需要能够在文章中从ng模型传递$scope.tag。然后post使用url中的post参数向服务器发出外部API请求的调用 // controller app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) { $scope.submit = function () { var recipe = $s
// 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;
});
};
}]);
//控制器
app.controller('MainCtrl',['$scope','$http',函数($scope,$http){
$scope.submit=函数(){
var recipe=$scope.tag;
$http.post('/api',{tag:recipe})
.然后(功能(响应){
$scope.recipeData=JSON.parse(response.data);
console.log(response.data);
});
};
//server.js
app.post('/api',函数(req,res){
var recipe=req.body.tag;
请求(“http://externalapi.com/api/search?key=xxx=“+配方、功能(错误、响应、正文){
res.json(正文);
});
});
//index.html
搜寻
---------重构代码----------
app.factory('searchFactory',['$http',函数($http){
var obj={};
obj.fetchRecipes=函数(){
返回$http.post(“/api”,{tag:“chicken”});
};
返回obj;
}]);
app.controller('MainController',['$scope','searchFactory',函数($scope,searchFactory){
$scope.submit=函数(){
searchFactory.fetchRecipes()
.成功(功能(响应){
$scope.recipeResults=响应;
});
};
}]);
将请求方法重构为,并将请求逻辑放入其中。例如,SearchService
因此,在MainController中注入SearchService并访问返回承诺的服务请求方法
例如:
app.controller('MainCtrl', ['$scope', 'SearchService',
function ($scope, SearchService) {
$scope.submit = function () {
var promise = SearchService.getRecipe( $scope.tag );
..
}
}
]);
看看社区推荐的一些样式指南和最佳实践。请参阅我的重构代码帖子。我不知道如何将$scope.tag传递到工厂以替换“鸡”。你有什么建议吗?