If you want to cache data you can do it in a number of ways. Two of approaches are here:-
Use $http inbuild cache that's simple (details in link above).
$http.get(url, { cache: true}).success(...);
Use $cacheFactory (details in link above)
Simply cache it inside your service:-
Service:-
var todoApp = angular.module("todoApp",[]);
todoApp.factory('dbService', ['$q','$http',function ($q , $http) {
var service ={};
service.localCache = {hasdata:false,data:{},lastLoaded:new Date()};
service.getUrl = function (urlToGet,burstCache) {
var svc=this;
var deferred = $q.defer();
if ((!burstCache)&&(svc.localCache)&&(svc.localCache.hasdata)) {
console.log('resolve from local cache');
return(svc.localCache.data);
}else{
var responsePromise = $http.get(urlToGet);
responsePromise.success(function (data, status, headers, config) {
svc.localCache={};
svc.localCache.hasdata=true;
svc.localCache.data=data;
svc.localCache.lastLoaded= new Date();
deferred.resolve(data);
console.log('resolve from ajax') });
responsePromise.error(function (data, status, headers, config) {
deferred.reject({ error: "Ajax Failed", errorInfo: data }); svc.localCache={}; });
}
return (deferred.promise);
}
return service;
}]);
Controller:-
todoApp.controller("ToDoCtrl",['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
$scope.todo={};
//Fetches the data from server. 'true' means burstCache
$timeout(function(){
dbService.getUrl('/api/userdata',true).then(function(resp){
$scope.todo=resp;
});},1);
//ReLoads the data from cache
$scope.reLoad=function(){
$scope.todo={};
$timeout(function() {$scope.todo=dbService.getUrl('/api/userdata');},1000);
};
}]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…