AngularJS promise is resolved before data is loaded

I haven’t used resolve but I’m throwing this out there just in case the issue you are having is related to binding to an array returned from a service.

If you are returning your cards array from a service and binding to it in the UI you may want to try to populate that same array instead of setting cards = data; (which will overwrite the local cards with a new array which is not bound to the UI).

Something like:

fetchCards: function() {
      var d = $q.defer();
      $http.get("data/cards.php").success(function(data) {
                      cards.length = 0;
                      for(var i = 0; i < data.length; i++){
                          cards.push(data[i]);
                      }
                      d.resolve();
                }).error(function(data, status) {
                      d.reject(status);        
                 });
               return d.promise;
      },

See this fiddle for a working example of what I’m trying to describe. Clicking the first button multiple times will update the view but once you click on the second button the binding will be broken.

The main difference between the two is:

  1. First button uses data.length = 0 and data.push() to retain the original array’s reference
  2. Second button overwrites the original data array reference with a new one using data = newArray

Update: Also, as Mark Rajcok, mentioned below you can use angular.copy to retain the original array’s reference by emptying it out and adding new ones from the source like this:

fetchCards: function() {
      var d = $q.defer();
      $http.get("data/cards.php").success(function(data) {
                      angular.copy(data, cards);
                      d.resolve();
                }).error(function(data, status) {
                      d.reject(status);        
                 });
               return d.promise;
      },

Leave a Comment