This question already has answers here:
How do I return the response from an asynchronous call?
                            
                                (39个答案)
                            
                    
                5年前关闭。
        

    

我有从服务返回的数据,但是我无法在控制器中使用该数据。请告诉我出什么事了;第一个console.log打印数据,而第二个console.log打印null。是因为范围问题吗?

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
getData = function() {
return $http({
    method: 'GET',
    url: 'https://www.example.com/api/v1/page',
    params: 'limit=10',
    headers: {}
 });


}
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
    $scope.data = dataResponse;
console.log($scope.data); //Prints my data here//
});
console.log($scope.data); //prints null//


});

最佳答案

第二个控制台日志将立即执行,因为它不等待服务方法被执行(请记住javascript是异步的),因此它不会等待。

myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
    $scope.data = dataResponse;
console.log($scope.data); //Prints my data here//
});
//outside service call and hence will print null with which it was initialized earlier
console.log($scope.data); //prints null//
});

关于javascript - 无法在 Controller 中使用angularjs服务返回的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25293127/

10-14 20:44
查看更多