加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 每5秒调用一次服务器 – 返回堆栈溢出错误

发布时间:2020-12-17 06:47:51 所属栏目:安全 来源:网络整理
导读:我想在一段时间内调用一个方法.我收到堆栈溢出错误.我究竟做错了什么: HTML: div ng-app="myApp" ng-controller="Ctrl" span{{calledServer}}/span/div JS: var app = angular.module('myApp',[]);app.controller("Ctrl",function($scope,repo,poollingFa
我想在一段时间内调用一个方法.我收到堆栈溢出错误.我究竟做错了什么:

HTML:

<div ng-app="myApp" ng-controller="Ctrl">
    <span>{{calledServer}}</span>
</div>

JS:

var app = angular.module('myApp',[]);

app.controller("Ctrl",function($scope,repo,poollingFactory) {
    $scope.calledServer;
    $scope.calledServer = poollingFactory.callFnOnInterval(function() {return repo.callServer(5);});
});

app.factory("repo",function() {

    function callServer(id){
        return "call server with id " + id;   
    }

    return {
        callServer: callServer
    };
});

app.factory("poollingFactory",function($timeout) {

    var timeIntervalInSec = 5;

    function callFnOnInterval(fn,timeInterval) {

        $timeout(callFnOnInterval,1000 * timeIntervalInSec);
        callFnOnInterval(fn,timeIntervalInSec);
    };

    return {
        callFnOnInterval: callFnOnInterval
    };
});

jsfiddle:http://jsfiddle.net/fq4vg/423/

解决方法

您有一个不检查任何前提条件的递归调用.

您的函数的注释版本:

function callFnOnInterval(fn,timeInterval) {

  //Schedule a call to 'callFnOnInterval' to happen in one second
  // and return immediately
  $timeout(callFnOnInterval,1000 * timeIntervalInSec);

  //Immediately make a call to 'callFnOnInterval' which will repeat
  // this process ad-infinitum
  callFnOnInterval(fn,timeIntervalInSec);

};

因为你不断地将调用推送到堆栈并且永远不会返回,所以它最终会耗尽空间.

由于$timeout服务返回一个promise,你可以使用它来完成更多的工作.

以下是您的服务应该是什么样子:

app.factory("poollingFactory",function ($timeout) {

   var timeIntervalInSec = 5;

   function callFnOnInterval(fn,timeInterval) {

       var promise = $timeout(fn,1000 * timeIntervalInSec);

       return promise.then(function(){
           callFnOnInterval(fn,timeInterval);
       });
   };

   return {
       callFnOnInterval: callFnOnInterval
   };
});

这里有一个示例jsFiddle来演示:http://jsfiddle.net/jwcarroll/cXX2S/

关于上面代码的一些注意事项.

您正在尝试将范围属性值设置为callFnOnInterval的返回值,但这不起作用.首先,它不返回任何东西.其次,因为它是一个异步调用,它最多可以返回一个promise.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读