控制器未从服务接收到数据

Data not received by Controller from Service

我的 Service 看起来像

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"}]

如您所见,logs 是空的,如何让它在数据来自 SupportService 时等待?

谢谢

当您说 $scope.logs = SupportService.data; 时,即刻发生 - 在您的 $http 通话完成之前。您需要等待 $http 调用完成 然后 提取数据。一般来说,最好的方法是 return $http 创建的承诺:

app.service('SupportService', function ($http, $q, $timeout) {
    return {
        getData: function() {
             return $http.get('/rest/report/logs');
        };
    };
});

并等待 promise 在您的控制器中解析:

var init = function () {
    SupportService.getData().then(function(response){
      $scope.logs = response;
      console.log("logs = " + $scope.logs);
    }
};
init();