denwo
denwo

Reputation: 91

Angular Factory data empty after $http

I'm trying to store data into a location[] array via http request method to a json file.

The problem is my listings controller always contains an empty array.

My Factory

app.factory('listing__data', function($http, $q){
  return {
    locations: '',
    makeRequest: function(url) {
      // Create the deffered object
      var deferred = $q.defer();

      $http.get('/'+url).then(function(resp) {
        deferred.resolve(resp.data);
      });
      return deferred.promise;
    },
    getUrl: function(params) {
      var url = "locations.json";

      if(!this.locations) {
        this.locations = this.makeRequest(url);
      }
      // Return the myObject stored on the service
      return this.locations;
    }
  };
});

My Controller

var listings__controller = app.controller('listings__controller', function($scope, distance__service, listing__data) {
    $scope.locations = [];

    listing__data.getUrl(distance__service.meters).then(function(data) {
    $.each(data.listings, function(i, item) {
          $scope.locations.push(item.location);
          console.log(item.location); // ** Shows Correct Object **
        });
    });
    console.log("How many inside:"+$scope.locations.length); // ** Empty - Shows 0 **
});

I can't seem to figure out why my $scope.locations = [] remains empty

Upvotes: 0

Views: 247

Answers (1)

Hugo Wood
Hugo Wood

Reputation: 2260

Even without the typo that JB Nizet mentioned, you will still see 0, because console.log("How many inside:"+$scope.locations.length); gets executed before the callback you pass to listing__data.getUrl(distance__service.meters).then, since the latter is asynchronous.

Remember that when using asynchronous functions, the flow of execution doesn't follow the order of lines of your source code.

promise.then(function () {
    console.log('inside callback');
});
console.log('outside callback');

will print outside callback then inside callback.

Consequently, if your going to use the value you store inside $scope.locations, you have to do it inside the callback.

Upvotes: 2

Related Questions