我尝试使用的承诺,在角度应用延迟执行。
我用两个函数$scope.checkQuestions()
和$scope.saveExerciseApi()
但问题是,之前,首先完成至极并不是我预期的第二个启动。
第一个呼叫承诺更新每个问题(与REST服务),然后更新$scope.formQuestion[]
数组其在页面上的形式使用。
$scope.Questions
和$scope.Exercises
已经答应对象更新,并在REST服务中创建的实体。
$scope.formQuestion
, $scope.formexercise
, $scope.exercises
是在网页上使用的数据。
$scope.checkQuestions = function(){
deferred = $q.defer()
for (i in $scope.formQuestion){
if ($scope.formQuestion[i].pk == null){ //Save
$scope.Questions.add($scope.formQuestion[i]).then(function(newquestion){
deferred.resolve(newquestion);
$scope.formQuestion[i] = newquestion;
});
}
}
return deferred.promise;
}
$scope.saveExerciseApi = function() {
if ($scope.formexercise.pk == null){ //Save
$scope.Exercises.add($scope.formexercise).then(function(newexercise){
$scope.exercises.push(newexercise);
$scope.showform = false;
});
}
}
$scope.saveExercise = function() {
$scope.checkQuestions().then($scope.saveExerciseApi);
}
编辑:
下面的变化不解决这个问题。
1) $scope.formexercise.questions
仍然是空的,
2)$ scope.saveExerciseApi推出从未发生
这有什么错在下面的逻辑? 有没有更好的和更清洁的方式来遍历和更新本地数据questions
后更新exercise
数据?
$scope.checkQuestions = function(){
deferred = $q.defer()
$scope.formexercise.questions = Array ();
for (i in $scope.formQuestion){
if ($scope.formQuestion[i].pk == null){
$scope.Questions.add($scope.formQuestion[i]).then(function(newquestion){
$scope.formQuestion[i] = newquestion;
$scope.formexercise.questions.push($scope.formQuestion[i].pk);
if ($scope.formQuestion.length == i+1){
deferred.resolve(newquestion);
}
});
} else {
$scope.Questions.edit($scope.formQuestion[i].pk, $scope.formQuestion[i]).then(function(updatequestion){
$scope.formexercise.questions.push($scope.formQuestion[i].pk);
if ($scope.formQuestion.length == i+1){
deferred.resolve(udpatequestion);
}
});
}
}
return deferred.promise;
}