简体   繁体   中英

$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?

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;
  }

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