简体   繁体   中英

How to know when angular has finished deferring

Hi I am struggling to understand Angular deffering and promises. I would like to know when all promises have been completed so i can hide a "loading" message. So here is my code example:

$scope.buildTeam = function () {
    $scope.Message = "loading...";

    var deferred = $q.defer();
    var promiseList = [];

    c = $scope.teamModels[0];

    for (index = 0; index < c.quantity; ++index) {
            var assignment = new teamAssignment(c.assignmentTypeId, $scope.parentAssignment.AssignmentId, c.description);
            promiseList.push(departmentService.addAssignment(assignment).then(function (result) {

                //added lead/captain. Now insert visually on page
                insertToScope($scope, result);

            }));
        }

    } 

    $q.all(promiseList).then(function () {
        deferred.resolve();
        $scope.Message = "Loaded.";
    });
}

The problem is Have is that $scope.Message shows "Loaded" well before the data has been inserted onto the page in the case of a large data pull. Could it be that i also need to defer insertToScope? InsertToScope simply reads:

function insertToScope($scope, a) {
   //get root scope
   var rs = angular.element("#ngRootContainer").scope();
   rs.parentAssig.push(a);
}

And the department service looks like this:

departmentModule.factory('departmentService', function ($http, $q) {
return {
    addAssignment: function(assignment){
        var deferred = $q.defer();
        $http.post('/Department/addAssignmentReturnAssignmentRow', assignment).success(deferred.resolve).error(deferred.reject);
        return deferred.promise;
    }
});

So my question is, what do i need to do to call a function only after all the promises are done? Thank you in advance for your feedback.

$q.all should do what you need. If your code doesn't work, I see two options:

  • You pass in a promiseList that does not contain all promises you want to wait for. Debug your code and check that all promises are passed in. Make sure it's an array you pass as the first parameter.
  • The promises you pass in resolve before you expect them to resolve. If you log 'A' in insertToScope , and 'B' in the then of your $q.all , you should see
 A ... A B 

in the console.

Here is a simple plunkr that shows how to use $q.all() : http://plnkr.co/edit/9QH9Y0w7DG0WCouMuX82?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM