I\'m building a web app using AngularJS. The app needs to poll a URL that returns JSON data and make that data available to any part of the app. From what I\'ve read so far,
I forked @ValentynShybanov's factory code and added intervals calls (every second, every 5 secs, etc), also you can stop and start the poller as you wish:
http://plnkr.co/edit/EfsttAc4BtWSUiAU2lWf?p=preview
app.factory('Poller', function($http, $timeout) {
var pollerData = {
response: {},
calls: 0,
stop: false
};
var isChannelLive = function() {
$http.get('data.json').then(function(r) {
if (pollerData.calls > 30 && pollerData.stop === false) { // call every minute after the first ~30 secs
var d = new Date();
console.log('> 30: ' + d.toLocaleString() + ' - count: ' + pollerData.calls);
pollerData.calls++;
$timeout(isChannelLive, 10000);
} else if (pollerData.calls > 15 && pollerData.calls <= 30 && pollerData.stop === false) { // after the first ~15 secs, then call every 5 secs
var d = new Date();
console.log('> 15 & <= 30: ' + d.toLocaleString() + ' - count: ' + pollerData.calls);
pollerData.calls++;
$timeout(isChannelLive, 5000);
} else if (pollerData.calls <= 15 && pollerData.stop === false) { // call every 1 second during the first ~15 seconds
var d = new Date();
console.log('<= 15: ' + d.toLocaleString() + ' - count: ' + pollerData.calls);
pollerData.calls++;
$timeout(isChannelLive, 1000);
}
pollerData.response = r.data;
});
};
var init = function() {
if (pollerData.calls === 0) {
pollerData.stop = false;
isChannelLive();
}
};
var stop = function() {
pollerData.calls = 0;
pollerData.stop = true;
};
return {
pollerData: pollerData, // this should be private
init: init,
stop: stop
};
});