Dimitrios Vythoulkas
Dimitrios Vythoulkas

Reputation: 621

Create a service to repeat functions in controller

I'm trying to write a service that simulates a polling functionality. My code is the following:

app.service('poller', ['$timeout',

    function($timeout) {

        return ({
            poll
        })

        function poll(e) {
            $timeout(function() {
                poll(e);
            }, 5000);
        }
    }
]);

When I inject it in my controller I try to use it like this:

poller.poll($scope.getNewMessages());

The weird thing is that it's only called once. Also when I try to use console log in the service like console.log(e) I get undefined. What am I doing wrong?

Upvotes: 0

Views: 30

Answers (1)

jcubic
jcubic

Reputation: 66488

You need to pass function as value to the poller function and you need to call the function:

app.service('poller', ['$timeout', function($timeout) {

        return ({
            poll
        });

        function poll(e) {
            e();
            $timeout(function() {
                poll(e);
            }, 5000);
        }
    }
]);

poller.poll($scope.getNewMessages);

Upvotes: 1

Related Questions