在工厂AngularJS

时间:2015-12-12 18:23:28

标签: javascript angularjs factory q angular-promise

我编写了这段代码,以递归方式进行多个$ http调用,并保存它在数组中返回的所有promise。然后我解决所有这些并将响应保存在另一个数组中。

我的问题是:如何将最后一个数组返回给我的控制器?

这里有一些代码

我的控制器:

app.controller('searchCtrl', function($scope, $http, $q, Data, RankServices) {
    $scope.imagesData = [];
    $scope.getImages = function(userId){

        //RankServices.getImages is my factory
        $scope.imagesData = RankServices.getImages(userId, undefined);

    }
}

我做了一个工厂来处理$ http请求:

app.factory('Data', function ($http, $q) {
  return {
    ajaxItems: function (url) {
      var deferred = $q.defer();
      $http.jsonp(url)
        .success(function (data, status, headers, config) {
          deferred.resolve(data);
        }).error(function (data, status, headers, config) {
          deferred.reject(data);
        });
      return deferred.promise;
    }
  }
});

这是使用上一个工厂执行$ http调用并在数组中保存所有promise,然后解析并保存数据的主工厂:

app.factory('RankServices', ['Data', '$q', function(Data, $q){
    var imagesDataPromises = [];
    var imagesData = [];

    return {
        getImages: function(userId, url){
          var self = this;
          if(url == undefined)
          var url = "http://www.exemple.com/getImages"+"&callback=JSON_CALLBACK";

          imagesDataPromises.push(Data.ajaxItems(url));

          Data.ajaxItems(url).then(function(response){
            if(response.pagination.next_url != undefined){
              //next_url comes inside the json it returned
              var next_url = response.pagination.next_url+"&callback=JSON_CALLBACK";
              self.getImages(userId, next_url);
            }
            else {
              return self.saveImages(imagesDataPromises)
            }
          });
        },

        saveImages: function(promisesArray) {
          var self = this;

          $q.all(promisesArray).then(function success(data){
            _.each(data, function(elem){
              //save on array only the data I want to
              imagesData.push(elem.data);
            });
            //imagesData is the array I want to return to the Controller
            return imagesData;
          });
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如何更改结构以确保从服务中获得承诺。您的控制器代码将变为:

$scope.getImages = function(userId){

    //RankServices.getImages is my factory
    RankServices.getImages(userId, undefined).then(function(data){
        _.each(data, function(elem){
          //save on array only the data I want to
          imagesData.push(elem.data);
        });
    });
}

明白我的意思?在控制器中有承诺!要实现此目的,您只需返回$q.all电话:

    saveImages: function(promisesArray) {
      var self = this;

      return $q.all(promisesArray)
    }