0

I have data returning from a service, but im unable to make use of that data in my controller. Please tell me what is wrong; the first console.log prints the data, but the second console.log prints null; is it because of scope issues?

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//

});

PSL
  • 123,204
  • 21
  • 253
  • 243
katpally
  • 11
  • 2
  • Even though the link talks about jquery ajax, it is a `generic asynchronous call` question. – PSL Aug 13 '14 at 18:10
  • Should learn basic of JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript, this is not AngularJS related – L42y Aug 13 '14 at 18:11
  • I already have the response, i need to pass this response to another http call. but im unable to use the returned response outside. – katpally Aug 13 '14 at 18:13
  • Just run it inside the then function or chain the promises... Or you can set a watch on `data` and do something... – PSL Aug 13 '14 at 18:18
  • thank you, it works when i run inside the then function :) – katpally Aug 13 '14 at 18:19

1 Answers1

1

The second console log gets executed immediately as it is not waiting for the service method to get executed (remember javascript is asynchronous) so it will not wait.

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//
});
V31
  • 7,626
  • 3
  • 26
  • 44