0

我必须使用AngularJS服务将数据加载到我的应用程序,这些应用程序的设置方式基本相同,尽管一个有效,一个无效。

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

我认为我的主要问题是$http呼叫是非阻塞的。例如,当我尝试console.log(i + " out of " + itemsToList.length)看到:

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

反过来,当我尝试uniqueLists像这样使用时,在我的应用程序中:

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

我得到错误TypeError: Object [object Object] has no method 'then'

有想法该怎么解决这个吗?api 调用工作得很好,$http.get所以我认为这只是一个阻塞/异步问题。

4

1 回答 1

1

试试这个未经测试的代码

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;
 })
于 2013-11-09T08:56:54.127 回答