0

I want to have a ticking clock on my website and it should display the actual time on the server. So I get the server time by using a factory

service.js

app.factory('UserService', function ($http, $q) {
    return {
        getcurrentdatetime: function () {
            var deferred = $q.defer();
            return $http.get('/LSBAMS/getcurrentdatetime')
                .then(function (response) {
                    deferred.resolve(response.data);
                    return deferred.promise;
                }, function (response) {
                    deferred.reject(response);
                    return deferred.promise;
                });
        }
});

and I called it in my controller

controller.js

app.controller('serverDateCtrl', ['$scope', 'UserService', '$timeout', function ($scope, UserService, $timeout) {
    $scope.clock = "loading clock...";
    $scope.tickInterval = 1000;
    UserService.getcurrentdatetime().then(function (msg) {
        
        $scope.d = msg[0]["newdatetime"];
        var tick = function () {
            var src = $scope.d;
            src = src.replace(/[^0-9 +]/g, '');
            var today = new Date(parseInt(src));
            $scope.clock = today; 
            $timeout(tick, $scope.tickInterval); 
        }    
        
        $timeout(tick, $scope.tickInterval);

    });
    
}]);

As you can see I called the getcurrentdatetime function from UserService service so I can get the current datetime on the server but the clock never ticks. I tried to put the getcurrentdatetime inside the tick function and it works well but it send a request to the server every second. What I want is to get the current time from the server and use it to start the clock. Can anyone help me please

Community
  • 1
  • 1
pryxen
  • 381
  • 2
  • 22

1 Answers1

1

The tick function should add time to the fetched datetime.

app.controller('serverDateCtrl', function ($scope, UserService, $timeout) {
    $scope.clock = "loading clock...";
    $scope.tickInterval = 1000;
    UserService.getcurrentdatetime().then(function (msg) {

        $scope.d = msg[0]["newdatetime"];
        var src = $scope.d;
        src = src.replace(/[^0-9 +]/g, '');
        var today = new Date(parseInt(src));
        $scope.clock = today;     

        $timeout(tick, $scope.tickInterval);

        function tick() {
            today = new Date(today.valueOf() + $scope.tickInterval);
            $scope.clock = today;
            $timeout(tick, $scope.tickInterval); 
        }
    });    
});

The service can be simplified:

app.factory('UserService', function ($http, $q) {
    return {
        getcurrentdatetime: function () {
            return $http.get('/LSBAMS/getcurrentdatetime')
                .then(function (response) {
                    return response.data;
                });
        }
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95