Reputation: 83
I have the following Javascript code in the controller of my web page.
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
});
$http({
method: 'GET',
url: $scope.properties.Properties.dataLocation
}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
The structure of the json file to be fetched is not the problem.
It is supposed to first run the $.getJSON command and afterwards run the $http-request, since the $http request gets its url from the variable that is defined in the $.getJSON part at the top but instead when i do a console.log(properties) just below it, it spits out "undefined".
Why is the code not executing in the order that it is written?
Upvotes: 0
Views: 627
Reputation: 3459
The code is executing in order that it's written, just callback functions are being executed when the corresponding requests are complete. So you should put the second call in the first callback:
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
$http({method: 'GET', url: $scope.properties.Properties.dataLocation}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
});
Upvotes: 1
Reputation: 944157
The same way that you have already got the line $scope.properties = data;
to run after the JSON has been received. You put it in the callback function you pass to getJSON.
Why is the code not executing in the order that it is written?
It is.
getJSON(url, foo)
means "Make an HTTP request to the url and set up an event handler to call foo
when the response is received".
You seem to be expecting it to wait for the response before doing anything else. That would lock up the UI and be horrible.
Upvotes: 0
Reputation: 3346
You could use the JQuery.done
, which will execute your code after your request has finished.
Example:
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
})();
Upvotes: 0
Reputation: 34
It is executed asynchronous so both call will be done independantly. $.getJSON has third parameter - success callback this is the way to sync those. http://api.jquery.com/jquery.getjson/
Not sure why you are mixing jQuery AJAX and Angular $http ?
Upvotes: 0