当已经有请求 运行 时,不要在 angular 中执行 $resource 请求

Don't execute a $resource request in angular when there is already a request running

我使用10秒的间隔发送请求获取最新数据:

var pollInterval = 10000;
var poll;

poll= $interval(function()
{
    getNewestData();//$resource factory to get server data
}, pollInterval );

这在 99% 的情况下工作正常,但如果网速真的很慢(我实际遇到过这种情况),它会在当前完成之前发送下一个请求。如果前一个仍然很忙,有没有办法跳过当前的间隔请求?显然我可以只使用布尔值来保持请求的状态,但我想知道是否有更好的(angular 原生)方法来做到这一点?

如何发出请求,然后等待它完成,然后等待 10 秒再再次发出相同的请求?沿着这条线:

            var pollInterval = 10000;

            var getNewestData = function () {
                // returns data in promise using $http, $resource or some other way
            };

            var getNewestDataContinuously = function () {
                getNewestData().then(function (data) {
                    // do something with the data

                    $timeout(function () {
                        getNewestDataContinuously();
                    }, pollInterval);
                });
            };

getNewestData 是实际发出请求的函数,returns 承诺中的数据。

获取数据后,$timeout 将启动一个定时器,定时器为 10 秒,然后重复该过程。

使用Resource对象的$resolved 属性检查前面的操作是否完成

来自文档:

The Resource instances and collections have these additional properties:

  • $promise: the promise of the original server interaction that created this instance or collection.

  • $resolved: true after first server interaction is completed (either with success or rejection), false before that. Knowing if the Resource has been resolved is useful in data-binding.

  • $cancelRequest: If there is a cancellable, pending request related to the instance or collection, calling this method will abort the request.

-- AngularJS ngResource $resource API Reference.