0

I want to have a list in sync, so I'm (right now) polling it every seconds. But I seem to have a problem - it does not work:

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

My goal is retrieving a list every X sec from the server that talks to the database. Anyone know why does does not spam "reload"? I only get it once

Jason94
  • 13,320
  • 37
  • 106
  • 184
  • You don't have any success callback to the promise in the timeout. And a timeout only executes once. Not repeatedly. – JB Nizet Feb 22 '15 at 14:42

2 Answers2

1

You are looking for $interval, and not $timeout.

from $interval docs:

Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.

and also:

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment.

Nitsan Baleli
  • 5,393
  • 3
  • 30
  • 52
0

As said by @Nitsan Baleli, you should use the service "$interval" and not "$timeout".

The question was asked here, please see the answer : Angular JS $timeout vs $interval

My goal is retrieving a list every X sec from the server that talks to the database.

I rewrote your code so that it matches your goal, it becomes:

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

See the plunkr demo here: http://plnkr.co/edit/xCbGGyKPTeJtg7TeKKyE?p=preview

Community
  • 1
  • 1
Aliz
  • 736
  • 1
  • 11
  • 25