Vaibhav Agrawal
Vaibhav Agrawal

Reputation: 29

$scope will be called before $http request in AngularJS

Whenever program runs it first call the $scope method and hence I cannot get any data which will load Dbdata from $http method.

var fileData = $http.get("JS/filesystemsdata.json").success(function (data) {
    $scope.DbData = data;
    $scope.isDBLoaded = true;
}).error(function (status) {
    alert(status);
    $scope.isDBLoaded = false;
});

var afterdata = $scope.getChilds("Common Files", "c,Program Files");
console.log(afterdata);

Upvotes: 0

Views: 97

Answers (3)

jitendra varshney
jitendra varshney

Reputation: 3562

if you want second thing execute after first thing then you can use $promise or then function(then is a combination of success and error and then is the new thing)

 var fileData = $http.get("JS/filesystemsdata.json").then(function(data){
    $scope.DbData = data;
    $scope.isDBLoaded = true;
    var afterdata = $scope.getChilds("Common Files", "c,Program Files");
    console.log(afterdata);
}, function(status){
    alert(status);
    $scope.isDBLoaded = false;
});

for then

https://docs.angularjs.org/api/ng/service/$http

for $q

https://docs.angularjs.org/api/ng/service/$q

Upvotes: 0

kefir500
kefir500

Reputation: 4404

Explanation

Contrary to your assumption stated in the question title, functions from your code will be called in a specified order:

  • $http.get
  • $scope.getChilds

However, the success and error callbacks for $http.get are asynchronous. That means that these functions will be called when the $http.get data is ready. I.e. this can take 1 millisecond or this can also take a whole minute (for example) – the success / error callbacks will be called when needed without stopping your main thread.

Solution

So the solution is to put the $scope.getChilds part in the success callback.
I suggest you to learn more about callbacks and promises to have a better understanding.

Side Note

Accroding to the AngularJS $http docs, success and error methods are deprecated, and you should use then instead:

The $http legacy promise methods success and error have been deprecated and will be removed in v1.6.0. Use the standard then method instead

Upvotes: 1

lin
lin

Reputation: 18392

Just put your function you like to execute into your success promise like:

var fileData = $http.get("JS/filesystemsdata.json").success(function (data) {
  $scope.DbData = data;
  $scope.isDBLoaded = true;
  var afterdata = $scope.getChilds("Common Files", "c,Program Files");
}).error(function (status) {
alert(status);
  $scope.isDBLoaded = false;
});

Upvotes: 1

Related Questions