IAmAkittycatAMA
IAmAkittycatAMA

Reputation: 245

AngularJS get request not returning data

I Have the following code in which I'm trying to get a JSON file and attach its contents to my $scope.

The first console.log returns the result that I need, but the second returns undefined.

What would be the correct way to write this so that the data is stored?

'use strict';

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

myApp.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}]);


myApp.controller('View1Ctrl', [

  '$scope',
  '$http',

  function($scope, $http) {
    $http.get('view1/info.json')
    .then(function(res){
      $scope.data = res.data.info
      console.log($scope.data)
    });

    console.log($scope.data)
}]);

Upvotes: 1

Views: 86

Answers (3)

Mathew Varughese
Mathew Varughese

Reputation: 16

The reason for this is with something called Promises. I definitely suggets looking into them. Here is kind of what happens in order:

$http.get('view1/info.json')

That tells javascript I want to get the JSON data. But it does not actually get it yet. Then, it does that console log.

console.log($scope.data)

Well $scope.data is undefined. Nothing has set it yet! Then, javascript actually gets the JSON data. When it gets the data, the function within the then is called. After this,

$scope.data = res.data.info
console.log($scope.data)

$scope.data is defined, which is why this console.log works. Read more about promises for more info!

Here is a good starting point: https://www.youtube.com/watch?v=wA0gZnBI8i4

Upvotes: 0

Watte
Watte

Reputation: 312

Well, your data is stored. But not at the time your second console.log() gets executed. The "then" promise/callback will run after your second console.log(). If you need $scope.data in your templates, this should work. Angulars digest cycle will be run after the callback of $https.

Upvotes: 0

Jonathan Lam
Jonathan Lam

Reputation: 17351

AngularJS's $http.get()'s then() callback is called asynchronously.

That means that in the callback, it will work, but not in the second one.

Upvotes: 1

Related Questions