Looking to implement a service that functions similarly to this example. Here is the code I have so far:
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;
});
In my controller, I am using it like this:
Poller.poll(
function(jsonAPI) {
console.log(jsonAPI);
},
function(error) {
console.log('Error:', error);
}
);
The data is being retrieved correctly, but there are a couple of issues:
- The callback function only gets called once and not at the specified $timeout interval. Adding conditionals in the service for callback and error handling prevents an error from occurring (
callback is not a function
). When I refresh or change the view, the callback function is triggered again. - The $timeout seems to be firing twice every 10 seconds instead of just once.