我试图将我所有的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();
}
});
有任何想法吗?
更新
MajoB的答案很棒。但是,对于模块化,我通常更喜欢在模型(服务)中而不是在控制器中处理数据处理。上面的代码的问题在于this
成功和错误功能中不可用。以下将打印“ 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) {
});;
}
});
或使用$ q创建自定义承诺:
this.loadHumanReadableNames = function() {
var deferred = $q.defer();
$http.get('http://proteomics.ysu.edu/secretomes/animal/index.php/api/get_human_readable_names/').success(function (data, status, headers, config) {
deferred.resolve({ data: data, tracker : 'ajax successful' })
});
return deferred.promise;
};
控制器:
app.controller('GlobalController', function($scope, Data) {
$scope.initializeData = function () {
//load human readable names
Data.loadHumanReadableNames().then(function (data) {
});;
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句