0

I have to AngularJS services to load data to my app which are set up in essentially the same way, although one works and one does not.

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'])
  .service('uniqueLists', function ($http) {
    console.log("Getting Unique Lists")
    var itemsToList = [
      'designer',
      'store',
      'category'
    ]
    var uniqueLists = {};
    var promise = (function(){
      console.log("Inside Function")
      for (var i = 0; i<itemsToList.length; i++){
        var item = itemsToList[i];
        uniqueLists[item] = [];
        $http.get('/api/uniques/' + item, { cache: true}).
        success(function (data){
          uniqueLists[item] = data.query;
          console.log(i + " out of " + itemsToList.length);
          if (i == itemsToList.length -1){
            return uniqueLists;
          }
        });
      };
    })();
    return promise;
})

I think my main issue is that the $http call is non-blocking. For instance, when I try to console.log(i + " out of " + itemsToList.length) I see:

3 out of 3
3 out of 3
3 out of 3

In turn, in my app when I try to use uniqueLists like so:

function homeCtrl($scope, $location, uniqueLists, userInfo){
  uniqueLists.then(function(obj){
  // Do stuff
  });
}

I get the error TypeError: Object [object Object] has no method 'then'

Any ideas on how to fix this? The $http.get api call works just fine so I think it's just a blocking/async problem.

1 Answer 1

1

Try this untested code

angular.module('myApp', [])
  .service('uniqueLists', function ($http, $q) {
  console.log("Getting Unique Lists")
  var itemsToList = [
    'designer',
    'store',
    'category']
  var uniqueLists = {};
  var promises = []

  console.log("Inside Function")
  for (var i = 0; i < itemsToList.length; i++) {
    var item = itemsToList[i];
    promises.push(http.get('/api/uniques/' + item, {
        cache: true
    }));
  };

  var defered = $q.defer();
  $q.all(promises).then(function (data) {
    for (var i = 0; i < data.length; i++) {
        var item = itemsToList[i];
        uniqueLists[item] = data[i].query;
    }
    defered.resolve(uniqueLists);
    }, function (error) {
    defered.reject(error)
  });

  return defered.promise;
 })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.