Search code examples
angularjshttpgetsecondsmethod-call

Angular.js Call $http.get every second


How can I call $http.get every second to update my page?

var app = angular.module("CompanionApp", []);

app.controller('LoginController', function ($scope, $http) {
    $scope.LoginSubmit = function() {
        $http.get('/api/player/' + $scope.name)
        .then(function(res) {
            $scope.connected = res.data.connected;
            $scope.health = res.data.health;
            $scope.armour = res.data.armour;
        })
    };
});

Solution

  • Try $interval :

    var app = angular.module("CompanionApp", []);
    
    app.controller('LoginController', function ($scope, $http, $interval) {
        var interval;
        $scope.LoginSubmit = function() {
          interval = $interval(function () {
            $http.get('/api/player/' + $scope.name)
            .then(function(res) {
                $scope.connected = res.data.connected;
                $scope.health = res.data.health;
                $scope.armour = res.data.armour;
            })
           }, 1000);
        };
    
        $scope.stopCalls = function(){ // incase you want to stop the calls using some button click
          $interval.cancel(interval);
        }
    });