我正在写一个连接到休息api的程序...但是工厂功能不起作用......虽然一切似乎都是正确的
工厂:
app.factory('publisherService', ['$http', function($http){
var services = {};
var userInfo = {};
services.getUser = function()
{
$http({method: 'GET', url: '/phoenix/publisher/user'}).success(function(data){
userInfo = data;
});
return userInfo;
};
return services;
}]);
控制器:
app.controller('publisher', ['$scope','publisherService', '$http',function($scope, publisherService,$http)
{
$scope.publisher = {};
$scope.publisher = publisherService.getUser();
}]);
当程序运行时,$ scope.publisher返回{}
但以下代码运行良好
app.controller('publisher', ['$scope','publisherService', '$http',function($scope, publisherService,$http)
{
$scope.publisher = {};
$http( {method: 'GET', url: '/phoenix/publisher/user'} ).success(function(data){
$scope.publisher = data;
});
}]);
答案 0 :(得分:0)
使用$ q解决问题... $ {article对此问题进行了详细解释。
答案 1 :(得分:0)
服务应该返回一个承诺:
app.factory('publisherService', ['$http', function($http){
var services = {};
var userInfo = {};
services.getUser = function()
{
var promise = $http({method: 'GET', url: '/phoenix/publisher/user'});
return promise;
};
return services;
}]);
然后控制器应该使用承诺:
app.controller('publisher', function($scope, publisherService,$http)
{
var promise = publisherService.getUser();
promise.then( function onSuccess(result) {
$scope.publisher = result.data;
});
});
服务返回空对象的原因是.success
方法作为参数给出的函数由$q
服务保存,直到XHR返回结果为止。 $q
存储函数,仅在结果可用时才调用它。在XHR完成之前,空对象被返回到服务功能。
让服务函数返回XHR承诺,然后让onSuccess
函数将结果放在$ scope上。