$http请求在一个请求中返回所有记录而不分页

$http request to return all records without pagination in a single request

本文关键字:请求 记录 返回 分页 一个 http      更新时间:2024-01-26

有4000多条记录。API最多返回1000条记录并具有分页。我调用这个函数(循环),并使用"skip"以1000条记录为间隔获取记录。

我一次需要所有记录,但下面的代码只返回前1000条记录。

  var array=[];
  function loop(skip){
     return $http({
            method: 'GET',
            url: myurl+'&$skip='+skip,
            timeout:5000
      }).success(function(res){
        if(res.d.length>0) 
            {
              Array.prototype.push.apply( array,res.d);
               loop(skip +1000);
            }
        return array;
      }).error(function(response,status,headers,config) {
      });
    }
    getAll = function() {
        return loop(0);
    }

我需要一个单一的请求才能获得总记录。但只有我得到了这部分的前1000条记录:(

    getAll().then(function() {
        console.log("in this part i need the array with my 4000 records")
    });

首先,角度文档的一个小注释:

$http遗留承诺方法successerror已被弃用。请改用标准然后的方法。如果$httpProvider.useLegacyPromiseExtensions设置为false,那么这些方法将抛出$http/legacy错误。

另一种解决方案:将累加器结果作为参数传递给循环函数

function loop(skip,result){
  result = result||[];//accumulator for result, init empty array if not pass
  return $http(
    {
          method: 'GET',
          url: myurl+'&$skip='+skip,
          timeout:5000
    }).then(function success(response){
      if(response.data.length > 0){
        Array.prototype.push.apply(result,response.data);
        return loop(skip+1000,result);
      }
      return result;
    },function error(){
    });
}

请注意,与当前代码的主要区别是在成功处理程序中调用loop函数之前的return

这项工作,因为如果从then函数返回promise,那么在返回promise后将应用下一个then

样本plunkr

应该可以使用一些递归承诺链接。试试这个

function getAll(page) {
    if (typeof page === 'undefined') {
        page = 0;
    }
    return $http.get(myurl, {$skip: page * 1000}).then(function(res) {
        var data = res.data;
        if (data.length > 0) {
            return getAll(page + 1).then(function(nextData) {
               return data.concat(nextData);
            });
        }
        return data;
    });
}

并称之为

getAll().then(function(allRecords) {
    console.log(allRecords);
});

这是一个被黑在一起的Plunker演示~http://plnkr.co/edit/ey8gdytvuBE6cpuMAtnB?p=preview

工作样品https://jsfiddle.net/coolbhes/xmqur1bq/(用承诺取代服务)

适用于您的代码如下:

var array = [];
function loop(skip, resolveHandle) {
    $http({
        method: 'GET',
        url: myurl + '&$skip=' + skip,
        timeout: 5000
    }).then(function successCallback(res) {
        if (res.d.length > 0) {
            Array.prototype.push.apply(array, res.d);
            loop(skip + 1000, resolveHandle);
        } else {
            //done with all requests;
            resolveHandle(array);
        }
    }, function errorCallback(rej) {
    });
};
function getAll() {
    return new Promise(function(resolve, reject) {
        loop(0, resolve);
    });
}
getAll().then(function(data) {
            console.log("in this part i need the array with my 4000 records", data)
        }