jhamm
jhamm

Reputation: 25032

$q not updating when the GET request returns

I am following this Angular tutorial on promises. I have a service that checks if an array is empty and if so, hits a REST service, returns a promise and updates the array. Here is the relative code:

  requestingProviders: [],
  getRequestingProviders: function() {
    var that = this;
    var deferred = $q.defer();
    if(this.requestingProviders.length === 0) {
      this.getResource().search({
        role: 'REQUESTING_PROVIDER'
      }, function(data) {
        that.requestingProviders = data.providers;
        deferred.resolve(data.providers);
      });
      return deferred.promise;
    } else {
      return that.requestingProviders;
    }
  }

The service is being called from a controller. Here is the code where it is being called:

$scope.providers = providerService.getRequestingProviders();

The REST call is made and returns fine, but the view is never updated. This is not working like the tutorial explained. Here is a plunker that shows what I am expecting. What am I doing wrong?

Upvotes: 3

Views: 76

Answers (1)

victormejia
victormejia

Reputation: 1184

You need to resolve your promise:

var prom = providerService.getRequestingProviders();

prom.then(function (data) {
   $scope.providers = data;
});

Also, change your code to always return the promise:

getRequestingProviders: function() {
    var that = this;
    var deferred = $q.defer();
    if(this.requestingProviders.length === 0) {
      this.getResource().search({
        role: 'REQUESTING_PROVIDER'
      }, function(data) {
        that.requestingProviders = data.providers;
        deferred.resolve(data.providers);
      });

    } else {
      deferred.resolve(that.requestingProviders);
    }
    return deferred.promise;
  }

Upvotes: 2

Related Questions