在angularJS中,如何将$http调用重构为服务?
我试图将下面的代码放入服务,但我似乎遗漏了一些东西!我必须单击按钮两次以更新表中所示的列表:在angularJS中,如何将$http调用重构为服务?,angularjs,angularjs-ng-repeat,Angularjs,Angularjs Ng Repeat,我试图将下面的代码放入服务,但我似乎遗漏了一些东西!我必须单击按钮两次以更新表中所示的列表: $scope.todoList = []; $scope.showTodoList = function(){ var url = '/api/v1/todo/list/'+$scope.report.from+'/'+$scope.report.to; $http({ method: 'GET', url: url }).then(function successC
$scope.todoList = [];
$scope.showTodoList = function(){
var url = '/api/v1/todo/list/'+$scope.report.from+'/'+$scope.report.to;
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
$scope.todoList = response.data;
}, function errorCallback(response) {
console.log(response);
});
}
所以我试着这样做:
angular.module('ReportController', []).controller('ReportController', ['$scope', '$http', '$rootScope', '$location', '$localStorage', '$routeParams', 'Report', 'Todo',
function ($scope, $http, $location, $localStorage, $routeParams, Report, Todo) {
$scope.todoList = [];
$scope.showTodoList = function(){
$scope.todoList = Report.getList($scope.report.from, $scope.report.to);
}
}]);
然后我创建了一个模块,并在那里添加了工厂
,并将此模块与所有其他模块一起加载
angular.module('ReportService', []).factory('Report', ['$q', '$filter', '$http', '$timeout', function ($q, $filter, $http, $timeout) {
var list;
function getList(date_from, date_to){
var url = '/api/v1/todo/list/'+date_from+'/'+date_to;
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
list = response.data;
}, function errorCallback(response) {
console.log(response);
});
return list;
}
return {
getList: getList
};
}]);
您的问题似乎是在返回列表时没有等待$http call的回调 您应该使ReportService的getList函数返回回调或承诺。它还将稍微改变您在ReportController中处理函数调用的方式 示例如何使用回调执行此操作: 报告服务:
angular.module('ReportService', []).factory('Report', ['$q', '$filter', '$http', '$timeout', function ($q, $filter, $http, $timeout) {
var list;
function getList(date_from, date_to, callback){
var url = '/api/v1/todo/list/'+date_from+'/'+date_to;
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
list = response.data;
return callback(list);
}, function errorCallback(response) {
console.log(response);
return callback(null);
});
}
return {
getList: getList
};
}]);
报告控制器:
angular.module('ReportController', []).controller('ReportController', ['$scope', '$http', '$rootScope', '$location', '$localStorage', '$routeParams', 'Report', 'Todo',
function ($scope, $http, $location, $localStorage, $routeParams, Report, Todo) {
$scope.todoList = [];
$scope.showTodoList = function(){
Report.getList($scope.report.from, $scope.report.to, function(res){
if(res) {
$scope.todoList = res;
}
});
}
}]);