I have controller and service with cached value.
app.service('nameService', ['$q','$http', function($q, $http){
var that = this;
that.name = null;
this.index = function(){
var deferred = $q.defer();
if (that.name !== null) {
// fired cahed value
console.log('cashed');
deferred.resolve(that.name);
} else {
$http.get('/api/name').success(
function(response) {
// fired request to server
console.log('server');
that.name = response.name;
deferred.resolve(that.name);
}
);
}
return deferred.promise;
}]);
When requests in controller send with interval like
app.controller('nameCtr', ['$scope', '$timeout', 'nameService'],
function($scope, $timeout, nameService){
nameService.index(); // console.log server
$timeout(function(){
nameService.index(); // console.log cached
},3000)
$timeout(function(){
nameService.index(); // console.log cashed
},6000)
}]);
It's all ok, first request fired server
, other fired cached
.
But if I send request without delay I send multiple requests to server. like:
...
nameService.index(); // console.log server
nameService.index(); // console.log server
nameService.index(); // console.log server
...
They all fired server
, but I need cached. I have multiple controllers with the same service. What the best way to send only one request to server?