我怎样才能一遍又一遍地获取列表?

时间:2015-02-22 14:32:02

标签: angularjs

我想要一个同步的列表,所以我(现在)每秒轮询一次。但我似乎有问题 - 它不起作用:

app.controller("MainController", function ($scope, $http, $timeout) {        
        $scope.responsePromise = $http.get("http://localhost:52219/API/GetList");

        $scope.responsePromise.success(function (data, status, headers, config) {
            $scope.model.list = JSON.parse(data);

            $timeout(function ()
            {
                console.log("reload");
                $scope.responsePromise = $http.get("http://localhost:52219/API/GetList");
            }, 1000);
        });

我的目标是每隔X秒从与数据库通信的服务器中检索一个列表。任何人都知道为什么不垃圾邮件“重装”?我只得到一次

2 个答案:

答案 0 :(得分:1)

您正在寻找$interval,而不是$ timeout。

来自$ interval docs的

  

Angular的window.setInterval包装器。 fn函数每延迟几毫秒执行一次。

还有:

  

注意:完成后,必须明确销毁此服务创建的间隔。特别是当控制器的范围或指令的元素被破坏时,它们不会被自动销毁。你应该考虑到这一点,并确保在适当的时候总是取消间隔。

答案 1 :(得分:0)

正如@Nitsan Baleli所说,你应该使用服务“$ interval”而不是“$ timeout”。

这里提出的问题,请参阅答案:Angular JS $timeout vs $interval

  

我的目标是每隔X秒从与数据库通信的服务器中检索一个列表。

我重写了你的代码,以便它符合你的目标,它变为:

app.controller("MainController", function ($scope, $http, $timeout) {   

   var $scope.model = {
        list:[]
   };

    var getData = function(){
        $http.get("http://localhost:52219/API/GetList").success(function(data){
            $scope.model.list = JSON.parse(data);
        });
    };

    getData(); // for the first call

    $interval(function (){
        getData();
    }, 1000);
});

请参阅此处的plunkr演示:http://plnkr.co/edit/xCbGGyKPTeJtg7TeKKyE?p=preview

相关问题