var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, personaService) {
personaService.startGetConsulta(2000).then(null, null, function(data){
$scope.data = data;
});
});
angular.module('plunker').service('personaService', PersonaService);
PersonaService.$inject = ['$http', '$q', '$interval'];
function PersonaService($http, $q, $interval){
var pollingInterval;
var count= 1;
this.getConsulta = getConsulta;
this.startGetConsulta = startGetConsulta;
this.stopGetConsulta = stopGetConsulta;
function startGetConsulta(interval){
if(pollingInterval){
return $q.resolve();
}
var deferred = $q.defer();
getConsulta().then(function(data){
deferred.notify(data);
}, function(response){
deferred.reject(response);
});
pollingInterval = $interval(function(){
console.log('Fireinterval');
getConsulta().then(function(data){
deferred.notify(data);
}, function(response){
deferred.reject(response);
});
count++;
}, interval);
return deferred.promise;
}
function stopGetConsulta(){
if(angular.isDefined(pollingInterval)) {
$interval.cancel(pollingInterval);
}
pollingInterval = null;
}
function getConsulta(){
return $http.get('https://jsonplaceholder.typicode.com/posts/' + count)
.then(function(response){ return response.data; } );
}
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{data | json}}!</p>
</body>
</html>
/* Put your css in here */