Javascript 控制器未从服务接收到数据
我的Javascript 控制器未从服务接收到数据,javascript,angularjs,angular-services,Javascript,Angularjs,Angular Services,我的服务看起来像 app.service('SupportService', function ($http, $q, $timeout) { var data = {result:[]}; var getData = function() { $http.get('/rest/report/logs') .then(function (response) { data.result = resp
服务
看起来像
app.service('SupportService', function ($http, $q, $timeout) {
var data = {result:[]};
var getData = function() {
$http.get('/rest/report/logs')
.then(function (response) {
data.result = response.data.result;
console.log("received logs:" + JSON.stringify(response.data.result));
});
};
getData();
return {
data: data.result
};
});
在我的控制器里,我做到了
var init = function () {
$scope.logs = SupportService.data;
console.log("logs = " + $scope.logs);
};
init();
当我运行这个程序时,我在控制台上看到的只是
logs =
received logs:[{"lastUpdated":"1430433095000","fileName":"java_pid1748.hprof","size":"2826611251","location":"/logs/java_pid1748.hprof"},{"lastUpdated":"1430862157000","fileName":"processor-debug.log","size":"910693","location":"/logs/processor-debug.log"},{"lastUpdated":"1430861106000","fileName":"processor-debug.log.1","size":"10242519","location":"processor-debug.log.1"},{"lastUpdated":"1430862156000","fileName":"processor-error.log","size":"1015578","location":"/logs/processor-error.log"},{"lastUpdated":"1430861106000","fileName":"logs","size":"204","location":"/logs"},{"lastUpdated":"1430862154000","fileName":"error.log","size":"2420","location":"/error.log"},{"lastUpdated":"1430862149000","fileName":"output.log","size":"71","location":"/output.log"}]
正如您可以看到的那样,日志
是空的,当数据来自支持服务
时,如何让它等待
感谢您说
$scope.logs=SupportService.data代码>立即发生-在$http
调用完成之前。您需要等待$http
调用完成,然后提取数据。通常,最好的方法是返回$http
创建的承诺:
app.service('SupportService', function ($http, $q, $timeout) {
return {
getData: function() {
return $http.get('/rest/report/logs');
};
};
});
并等待承诺在控制器中解决:
var init = function () {
SupportService.getData().then(function(response){
$scope.logs = response;
console.log("logs = " + $scope.logs);
}
};
init();
谢谢,下次我会记住这一点。这对我很有效