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

时间:2015-12-06 20:54:55

标签: 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 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
    };

  }]);

1 个答案:

答案 0 :(得分:2)

您的问题似乎是您在返回列表时没有等待$ 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;
        }
      });
    }
}]);