【问题标题】:How to fill variable with values by service (AngularJS)如何通过服务(AngularJS)用值填充变量
【发布时间】:2017-09-01 04:10:25
【问题描述】:

调用服务后我的变量没有值。我将success函数定义为一个单独的函数,并在.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() 的代码
  • 为什么不直接在function success 中设置vm.fillVar 并避免使用successData 变量
  • 您期望在异步调用之外同步执行。希望你了解核心JS
  • @sand 因为我想将success-方法也用于同一控制器中的其他服务,所以最好阅读。
  • @yuro 检查我的答案,它应该适合你

标签: javascript angularjs angularjs-scope angularjs-service


【解决方案1】:

这段代码是异步的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

then 方法返回一个允许方法链接的 Promise。

编辑

如果您想处理错误情况,只需使用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

【讨论】:

  • 什么是,什么时候会出现错误?我在error函数中定义了err变量,它会立即在视图中显示错误。
  • 感谢您的支持。目前这是一个好方法:)
  • 不客气,很高兴这段代码对你有帮助:)
【解决方案2】:
// 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);
}

【讨论】:

  • 那个解决方案我已经知道了。但不是我正在寻找的预期解决方案。不过感谢您的支持:)
猜你喜欢
  • 2016-05-26
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多