让AngularJS跳过运行的消化循环,如果$ http.get()导致没有新的数据 [英] Make AngularJS skip running a digest loop if $http.get() resulted in no new data

查看:576
本文介绍了让AngularJS跳过运行的消化循环,如果$ http.get()导致没有新的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前轮询服务器以检查是否有新的数据,然后相应地更新在AngularJS应用模型。 He're约我在做什么:

I'm currently polling the server to check for new data, and then update the model in an AngularJS app accordingly. He're roughly what I'm doing:

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,但不知何故跳过摘要,如果一切都没有改变?

This works fine, but most of the requests will not result in any new data or data changes, but the $http service doesn't really know/care and will still trigger a digest cycle. I feel this is unnecessary (since the digest cycle is one of the heaviest operations in the app). Is there any way to still be able to use $http but somehow skip the digest if nothing has changed?

一个解决办法是不使用$ HTTP但jQuery的代替,然后调用$适用于让角知道该模型已经改变:

One solution would be to not use $http but jQuery instead, and then call $apply to let Angular know that the model has changed:

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);

虽然这似乎工作,我不知道这是一个好主意。我仍然喜欢用纯角如果可能的话。

While this seems to work, I'm not sure it's a good idea. I would still like to use pure Angular if possible.

任何人有任何建议,为改善上述方法或一个更优雅的解决方案完全?

P.S。我使用的,而不是$超时setInterval的原因是因为$超时也会触发摘要周期这将是在这种情况下没有必要,只添加到问题。

推荐答案

网络插座似乎在这里得到最完美的解决方案。这样,你不需要轮询服务器。当数据或内容发生了变化,服务器可以告诉您的应用程序。

Web sockets would seem to be the most elegant solution here. That way you don't need to poll the server. The server can tell your app when data or anything has changed.

这篇关于让AngularJS跳过运行的消化循环,如果$ http.get()导致没有新的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆