好的,所以我有一个带有执行HTTP请求的函数的服务,并且返回的值设置为$scope
,但这不起作用,因为似乎$scope
没有等待AJAX呼叫。我如何从控制器外部的服务函数返回AJAX结果?
示例:
//Controller
app.controller('Controller', function($scope, $http, Service){
// $scope WILL NOT BE SET TO THE VALUE RETURNED, the returned value is UNDEFINED
$scope = Service.getData();
}
// Get server data from service function
app.service('Service', function ($http){
this.getData = function(){
//Get server data
return { data: result }
}
}
答案 0 :(得分:0)
尝试将服务调用放入resolve函数并将结果注入控制器。
这篇博文有一个很好的例子:http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx
答案 1 :(得分:0)
你不能等待ajax通话。这就是为什么AJAx中的“A”代表异步的原因。您可以尝试同步调用(应该避免)或尝试使用回调函数来设置范围。
例如,
//service
this.getData=function(callback){
callback({data:result});
}
//controller
Service.getData(function(response){
$scope = response;
})
答案 2 :(得分:0)
一旦Ajax调用完成,您将需要运行回调函数。所以它看起来像这样。
//Controller
app.controller('Controller', function($scope, $http, Service){
// $scope WILL NOT BE SET TO THE VALUE RETURNED, the returned value is UNDEFINED
Service.getData(function(data) {
$scope = data;
});
}
// Get server data from service function
app.service('Service', function ($http){
this.getData = function(callback){
//Get server data
callback({data: result});
}
}