I'm trying to create a service similar to this example. My code is the following:
app.service('Poller', function ($q, $http, $timeout) {
var notification = {};
notification.poll = function (callback, error) {
return $http.get('https://someapi.com').then(function (response) {
if (typeof response.data === 'object') {
if (callback){
callback(response.data);
console.log('tick');
}
} else {
if (error) {
error(response.data);
}
}
$timeout(notification.poll, 10000);
});
}
notification.poll();
return notification;
});
And I try to use it in my controller like this:
Poller.poll(
function(jsonAPI) {
console.log(jsonAPI);
},
function(error) {
console.log('Error:', error);
}
);
The data are being fetched correctly but there seems to be two problems.
- The callback function is called only once and not according to the $timeout. I added the conditionals in the service for callback end error because without them it throws an error
callback is not a function. When I refresh or change the view the callback function is again called. - The $timeout seems to be triggered twice every 10 seconds and not once.