在AngularJS服务中使用$http

在AngularJS服务中使用$http,angularjs,Angularjs,我正在尝试将所有AJAX从Angular控制器移动到服务中。我的代码在控制器中运行良好,但我无法在服务中运行相同的$http请求。当我运行以下代码时,Data.tracker被设置为“函数已启动”,然后再也不会更改 app.service("Data", function($http) { this.tracker = "not started"; this.loadHumanReadableNames = function() { this.tracker = "funct

我正在尝试将所有AJAX从Angular控制器移动到服务中。我的代码在控制器中运行良好,但我无法在服务中运行相同的$http请求。当我运行以下代码时,
Data.tracker
被设置为“函数已启动”,然后再也不会更改

app.service("Data", function($http) {

this.tracker = "not started";

this.loadHumanReadableNames = function() {
        this.tracker = "function started";
        $http.get('http://proteomics.ysu.edu/secretomes/animal/index.php/api/get_human_readable_names/').
        success(function(data, status, headers, config) {
            this.tracker = "ajax successful";
        }).
        error(function(data, status, headers, config) {
            this.tracker = "ajax failed";
        });
    };
});

app.controller('GlobalController', function($scope, Data) {

    $scope.Data = Data;

    $scope.initializeData = function () {
        //load human readable names
        Data.loadHumanReadableNames();
    }
});
有什么想法吗


更新

马约布的回答很有效。然而,对于模块化,我通常更喜欢在模型(服务)中而不是在控制器中处理数据处理。上述代码的问题在于,
在成功和错误函数中不可用。下面将打印“ajax成功”:

在职期间:

app.service("Data", function($http) {

this.tracker = "not started";
var self = this;

this.loadHumanReadableNames = function() {
        this.tracker = "function started";
        $http.get('http://proteomics.ysu.edu/secretomes/animal/index.php/api/get_human_readable_names/').
        success(function(data, status, headers, config) {
            self.tracker = "ajax successful";
        }).
        error(function(data, status, headers, config) {
            self.tracker = "ajax failed";
        });
    };
});

您可以从您的服务中回报承诺:

this.loadHumanReadableNames = function() {            
        return $http.get('http://proteomics.ysu.edu/secretomes/animal/index.php/api/get_human_readable_names/');            
    };
});
控制器

app.controller('GlobalController', function($scope, Data) {   


    $scope.initializeData = function () {
        //load human readable names
        Data.loadHumanReadableNames().success(function (data, status, headers, config) {

        });;
    }
});
或通过以下方式创建自定义承诺:

控制器:

app.controller('GlobalController', function($scope, Data) {   


        $scope.initializeData = function () {
            //load human readable names
            Data.loadHumanReadableNames().then(function (data) {

            });;
        }
    });

成功回调函数中的该关键字引用的是本地范围,而不是父对象。
所以它不会改变。尝试分配一些变量,然后您可以在成功回调函数中更改该变量

服务/提供程序是单例(每个应用程序一个服务实例),它们不共享任何父作用域,如果包含$rootScope,它们只能访问$rootScope
app.controller('GlobalController', function($scope, Data) {   


        $scope.initializeData = function () {
            //load human readable names
            Data.loadHumanReadableNames().then(function (data) {

            });;
        }
    });