如何将HTTP请求从AngularJS控制器移出到服务中?

Ala*_*an2 7 angularjs

我有以下代码片段:

    angular.module('test', []).controller('TestCtrl', function ($scope, $http) {
        $scope.selectedTestAccount = null;
        $scope.testAccounts = [];

        $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            params: { applicationId: 3 }
        }).success(function (result) {
            $scope.testAccounts = result;
        });
    }
Run Code Online (Sandbox Code Playgroud)

有人向我建议我应该考虑为$ http请求创建服务.有人可以给我一个例子,告诉我如何为上面的代码执行此操作.特别是我不知道如何设置服务并让控制器注入它.

Foo*_*o L 14

您的服务需要看起来像这样:

angular.module('testaccount', []).
factory('TestAccount', function($http) {
  var TestAccount = {};
  TestAccount.get = function(applicationId, callback) {
    $http.get('/Admin/GetTestAccounts?applicationId=' + applicationId).success(function(data) {
      callback(data);
    });
  };
  return TestAccount;
});
Run Code Online (Sandbox Code Playgroud)

您的控制器需要注入服务,使用参数调用服务对象,并发送回调函数:

angular.module('test', ['testaccount']).controller('TestCtrl', function ($scope, TestAccount) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    TestAccount.get(3, function (data) {
      $scope.testAccounts = data;
    })
}
Run Code Online (Sandbox Code Playgroud)

阅读本教程中有关服务依赖项注入的更多信息