如何在AngularJS结束之前加载$ https的响应

时间:2014-11-28 01:54:40

标签: angularjs node.js http

我需要从数据库加载2000行,如果我只是加载api(domain.com/api/contacts/)访问它们,它加载得足够快但如果我尝试使用ng-repeat使用$ http打印它们加载相同数量的数据需要大约10秒钟

然后我的问题是:是否可以在结束前加载$ http的响应?

我不想使用插件来进行延迟加载,因为从开始时加载所有行以进行搜索非常重要

这是我正在使用的代码

 $http.get('/api/contacts/').success(function (data) {
   $scope.contacts = data
 }).error(function (err) {
   console.log(err)
 });

然后我使用

打印结果
<ul>
  <li ng-repeat="c in contacts">{{c.contact_name}}</li>
</ul>

我看到的是,当我通过浏览器调用api时,结果会在请求结束前开始加载,另一方面会在请求结束前对结果进行角度打印。

1 个答案:

答案 0 :(得分:0)

我说这需要太长时间,因为角度必须执行大型DOM操作......

如果以较小的块分解大型数组,将每个块单独添加/追加到ngRepeat中使用的属性会怎样?

//on $htttp success...
var dataRows = data; //data is your array with 2000 items
var delay = 0; //in milliseconds

//var to be used in ngRepeat
$scope.rows = [];

//each loop will extract the first objects from the array until the array is empty
while(dataRows.length) {
    delay += 20; //time span between every timeout call
    //using $timeout so it creates a new thread (don't lock UI)
    $timeout(function () {

        //take the first 50 items from the Array
        var thisChunk = dataRows.splice(0, 50);

        //append the 50 items to the $scope var
        $scope.rows.push.apply($scope.rows, thisChunk);

    }, delay);
}

然后,您可以调整每次要添加的项目数,以及每次超时调用之间的毫秒数。