在angularJS中,如何将$http调用重构为服务



我试图将下面的代码放入服务中,但似乎遗漏了一些东西!我必须点击两次按钮才能更新表中显示的列表:

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

然后我创建了一个模块,在那里添加了factory,并将这个模块与所有其他一起加载

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调用的回调。

您应该使ReportService的getList函数返回回调或Promise。它还将稍微改变您在ReportController中处理函数调用的方式。

示例如何使用回调进行此操作:

ReportService:

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

ReportController:

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

最新更新