2017-06-23 55 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

是的,這與你的答案使竅門。請編輯並將此評論添加到答案中。謝謝! –