首先,你的success()
handler 只是返回数据,但不会返回给调用者getData()
因为它已经在回调中了。$http
是一个异步调用,返回一个$promise
,因此您必须在数据可用时注册回调。
我建议查找 Promises 和$q 库 http://docs.angularjs.org/api/ng.%24q在 AngularJS 中,因为它们是在服务之间传递异步调用的最佳方式。
为简单起见,以下是使用调用控制器提供的函数回调重写的相同代码:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
Now, $http
实际上已经返回了一个 $promise,所以可以重写:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
最后,有更好的方法来配置$http
为您处理标头的服务config()
设置$httpProvider
。结帐$http 文档 http://docs.angularjs.org/api/ng.%24http举些例子。