Controller未从服​​务部门收到数据

时间:2015-05-05 21:47:23

标签: javascript angularjs angular-services

我的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时等待它?

由于

1 个答案:

答案 0 :(得分:1)

当您在$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();