javascript - Angular1.x如何将某个$http请求抽取成公共代码,以便重复使用?
本文介绍了javascript - Angular1.x如何将某个$http请求抽取成公共代码,以便重复使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
mainApp.config(function($stateProvider, $urlRouterProvider) {
//路由配置
$stateProvider.state('home', {
url: '/home',
templateUrl: 'home.html',
controller : function($scope,$http){
//获取列表数据的方法 Start.........
$scope.getHomeData = function(){
$http({
url : '/getHomeDataList',
method : 'POST'
}).then(function(){
//请求成功
},function(){
//请求失败
})
};
//获取首页数据的方法 End..........
}
});
});
如上代码定义的,获取列表数据的方法,如何把它独立出来?以便可以在初始化加载、分页、新增以及删除等情况下调用?
解决方案
把所有接口都封装到service层
angular.module("MyController", [])
.controller("IndexController", ["$scope", "githubService", function($scope, githubService){
$scope.name = "dreamapple";
$scope.show = true;
githubService.getPullRequests().then(function(result){
$scope.data = result;
},function(error){
$scope.data = "error!";
},function(progress){
$scope.progress = progress;
$scope.show = false;
});
}]);
angular.module("MyService", [])
.factory('githubService', ["$q", "$http", function($q, $http){
var getPullRequests = function(){
var deferred = $q.defer();
var promise = deferred.promise;
var progress;
$http.get("https://api.github.com/repos/angular/angular.js/pulls")
.success(function(data){
var result = [];
for(var i = 0; i < data.length; i++){
result.push(data[i].user);
progress = (i+1)/data.length * 100;
deferred.notify(progress);
}
deferred.resolve(result);
})
.error(function(error){
deferred.reject(error);
});
return promise;
}
return {
getPullRequests: getPullRequests
};
}]);
这篇关于javascript - Angular1.x如何将某个$http请求抽取成公共代码,以便重复使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文