如何通过服务用值填充变量 (AngularJS)

How to fill variable with values by service (AngularJS)

调用服务后我的变量没有值。我将成功函数定义为一个单独的函数,并在 .then() 方法中调用它,代码如下:

// 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
}

我不明白为什么调用success函数后successData变量为空。有点混乱...有人解决这个问题吗?

这段代码是异步的 CrudSvc.GetAllData().$promise.then(success, error); 所以如果你想在那之后执行一些事情,你应该将你的代码更改为:

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

您可以阅读有关 then 链接的内容 HERE

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

编辑

如果您想处理错误情况,只需使用 reject 函数,如下所示:

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
// 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(function(response) {
successData = response;
    console.log('Success Variable: ', successData); //--> here, the success variable now contains no data
          vm.fillVar = successData;
          console.log('fillVar for the view: ', vm.fillVar); //--> fillVar is empty, why??
}, function(error) {
});


      }
   }, 500);
}