【问题标题】:Loading of paginated data from API从 API 加载分页数据
【发布时间】:2017-10-02 06:13:23
【问题描述】:

我正在开发一个当前需要我从 API 加载所有项目的系统。

API 内置有分页功能。我多次调用 API 并 $http.get 诅咒系统不响应。例如,一旦我加载需要多次调用 API 的页面(如 50 到 80 次,具体取决于页面数量),几分钟内我所做的任何事情都不会响应,直到 API 调用几乎完成.我已经尝试了很多方法,但都行不通。

$scope.loadAllPagedItems = function (category_uuid, max_pageitem, item_perpage) {
    for (var a = 0 ; a < max_pageitem; a++) {
        itemResource.findItems(category_uuid, item_perpage, a).then(function (response) {
            if (response.data.data.length > 0) {
                for (var a = 2 ; a < $scope.categories.length; a++) {
                    if ($scope.categories[a][0].category_uuid == response.data.data[0].category_uuid) {
                        for (var j = 0; j < response.data.data.length; j++) {
                            $scope.categories[a][0].data.push(response.data.data[j]);
                        }
                    }
                }
            }
        }, function (error) {
            console.log(error);
        })
    }
}

有什么办法可以做得更好吗?

【问题讨论】:

    标签: angularjs angular-promise angularjs-http


    【解决方案1】:

    从异步 API 中按顺序检索分页数据

    $scope.loadAllPagedItems = function(category_uuid, max_pageitem, item_perpage) {
        var promise = $q.when([]);
        for (let a = 0 ; a < max_pageitem; a++) {
            promise = promise
              .then(function(dataArray) {
                var p = itemResource.findItems(category_uuid, item_perpage, a);
                p = p.then(function (response) {
                      return dataArray.concat(response.data.data);
                });
                return p;
            });
        };
        return promise;
    };
    

    上面的例子,顺序执行XHRs,并使用数组concat方法将解析后的数组合并成一个数组。

    用法:

    $scope.loadAllPagedItems(category, pages, itemsPerPages)
      .then(function(finalArray) {
        console.log(finalArray);
    }).catch(function(response) {
        console.log("ERROR ",response.status);
        throw response;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多