小编典典

如果$ http.get()没有新数据,则使AngularJS跳过运行摘要循环

angularjs

我目前正在轮询服务器以检查新数据,然后相应地在AngularJS应用中更新模型。他大概就是我在做什么:

setInterval(function () {
    $http.get('data.json').then(function (result) {
        if (result.data.length > 0) {
          // if data, update model here
        } else {
          // nothing has changed, but AngularJS will still start the digest cycle
        }
    });
}, 5000);

这可以正常工作,但是大多数请求都不会导致任何新数据或数据更改,但是$
http服务并不真正知道/关心它,仍然会触发摘要周期。我觉得这是不必要的(因为摘要循环是应用程序中最重的操作之一)。 有什么办法仍然可以使用$
http,但是如果没有任何变化,则以某种方式跳过摘要?

一种解决方案是不使用$ http而是使用jQuery,然后调用$ apply使Angular知道模型已更改:

setInterval(function () {
    $.get('data.json', function (dataList) {
        if (dataList.length > 0) {
            // if data, update model
            $scope.value = dataList[0].value + ' ' + new Date();

            // notify angular manually that the model has changed.
            $rootScope.$apply();
        }
    });
}, 5000);

尽管这似乎可行,但我不确定这是个好主意。如果可能,我仍想使用纯Angular。

有人对以上方法的改进或更优雅的解决方案有任何建议吗?

PS我之所以使用setInterval而不是$ timeout的原因是因为$
timeout还会触发一个摘要循环,在这种情况下这是不必要的,只会添加到“问题”中。


阅读 278

收藏
2020-07-04

共1个答案

小编典典

Web套接字似乎是这里最优雅的解决方案。这样,您无需轮询服务器。当数据或任何内容发生更改时,服务器可以告诉您的应用程序。

2020-07-04