Search code examples
javascriptangularjsangularjs-scopeangularjs-service

How to fill variable with values by service (AngularJS)


My variable has no value after calling the service. I defined the success function as a separate function and called it in the .then() method, here's the code:

// Code inside the Ctrl:
var successData = null;
vm.fillVar = null;
vm.loadData = loadData;

// service func
function loadData() {
   return $timeout(function () {
      vm.fillVar = vm.fillVar || [];

      if (vm.fillVar == undefined || vm.fillVar.length == 0) {
          CrudSvc.GetAllData().$promise.then(success, error);

          console.log('Success Variable: ', successData); //--> here, the successData variable contains no data
          vm.fillVar = successData;
          console.log('fillVar for the view: ', vm.fillVar); //--> fillVar is empty, why??
      }
   }, 500);
}

// success func
function success(res) {
   console.log('var res: ', res); //--> res contains data
   successData = res;
   console.log('success func: ', successData); //--> the variable contains data
}

I don't understand why the successData variable is empty after calling the success function. It is a bit confusing... Has anyone a solution for this issue?


Solution

  • This code is async CrudSvc.GetAllData().$promise.then(success, error); so if you want to execute something after that you should change your code to:

    CrudSvc.GetAllData().$promise.then(success, error).then(function(){
         // this code is executed after all the previous code is done and succeed
         console.log('Success Variable: ', successData); 
         vm.fillVar = successData;
         console.log('fillVar for the view: ', vm.fillVar); 
    });
    

    You can read about then chaining HERE

    The then method returns a Promise which allows for method chaining.

    EDIT

    If you want to handle error situation simply use reject function like this:

    CrudSvc.GetAllData().$promise.then(success, error).then(function(){
         // this code is executed if previous success 
    }, function(){
         // this code is executed if previous error
    }); // This is how you do further error handling via this approach