2017-06-23 66 views
1

我是AngularJS的一名新手,并且正在努力应对API。我已经实现了一个save()功能在我的控制器,以获得:等待一个函数完成多个资源调用

  1. 的调控版本保存的
  2. 一旦调控版本保存,其所有安装类型都保存在一个异步并行方式
  3. saved!日志显示一切完成后,(在我的实际应用中我想去这里其他应用程序的状态)

这就是我目前在我的控制器代码:

var saveRegulationInstallationTypes = function (result) { 
    var saveOperations = []; 
    angular.forEach(vm.installationTypeRegs, function (
      installationTypeReg, key) { 
     installationTypeReg.regulationVersion = result; 
     var res = InstallationTypeReg.update(installationTypeReg, function() { 
       console.log('Installation type updated'); 
      }); 
     saveOperations.push(res); 
    }); 
    return $q.all(saveOperations); 
} 

function save() { 
    var regulationVersionSaved = RegulationVersion.update(vm.regulationVersion); 
    return regulationVersionSaved.$promise.then(
     function (result) { 
      saveRegulationInstallationTypes(result).then(console.log('saved!')); 
    }); 
} 

RegulationVersionInstallationTypeReg在返回$resource方法在每个实体的HTTP业务的服务。执行save()方法时的问题是,我在Installation type updated之前得到了saved!日志。我想,当我从函数返回q.all时,它应该等待在调用回调之前完成所有内部操作。

我在做什么错?

回答

1

似乎有两个问题:1)“saveOperations.push(res);” - 应该是“saveOperations.push(res。$ promise);” - 和数组一样,它应该存储承诺而不是整个对象。 2)saveRegulationInstallationTypes(result).then(console.log('saved!'));应该是saveRegulationInstallationTypes(result).then(function(){console.log('saved!')});

+0

它是有道理的,但即使我改变它来存储承诺,日志记录顺序保持不变。 –

+0

尝试使用以下更改: “saveRegulationInstallationTypes(result).then(console.log('saved!'));” 到 “saveRegulationInstallationTypes(result).then(function(){console.log('saved!')});” –

+0

是的,这与你的答案使窍门。请编辑并将此评论添加到答案中。谢谢! –