IAmAkittycatAMA IAmAkittycatAMA - 5 months ago 10
Javascript Question

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)
}]);

Answer

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

Comments