【问题标题】:how can I load response of $https before it ends in AngularJS如何在 $https 以 AngularJS 结束之前加载响应
【发布时间】:2015-01-26 15:42:01
【问题描述】:

我需要从数据库加载 2000 行,如果我访问它们只是加载 api (domain.com/api/contacts/),它加载速度足够快,但如果我尝试使用 $http 使用 ng-repeat 打印它们加载相同数量的数据大约需要 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 时,结果在请求结束之前开始加载,另一方面,角度打印结果直到请求结束。

【问题讨论】:

  • 什么需要 10 秒?调用$http,还是使用 ng-repeat 呈现该数据所需的时间?
  • 消耗响应并呈现响应所需的时间
  • 不可能通过所提供的信息判断问题可能是什么,或者您到底在问什么。 chrome 开发工具的网络选项卡中的时间是什么样的?如果将数据作为 javascript 对象粘贴到代码中,是否仍需要 10 秒才能呈现?尝试将数据加载到一个单独的变量中,并创建一个用于调试的按钮来设置ng-repeat 中使用的变量,这将告诉哪个需要太长时间。尝试使用angularjs batarang 分析代码。
  • 在您的问题中也显示您的确切 html 和一些示例对象,更好的标题应该是“为什么这个 ng-repeat 需要这么长时间?”可能有很多东西。如果您要创建一个包含 100 列的表,则可能只需要那么长的时间。如果您在 2000 个复杂对象上使用过滤器或 orderBy,则可能只需要很长时间。

标签: angularjs node.js http


【解决方案1】:

我会说这需要很长时间,因为 Angular 必须进行大型 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);
}

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

【讨论】:

  • 非常感谢!我会试一试,顺便说一句,是否可以使用像流一样逐渐加载的东西?
猜你喜欢
  • 2023-02-02
  • 2017-10-28
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多