我有从服务返回的数据,但我无法在我的控制器中使用该数据。请告诉我出了什么问题;第一个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//
});
答案 0 :(得分:1)
第二个控制台日志立即执行,因为它没有等待服务方法执行(记住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//
});