After next(Route) to other page, come back it still call back the link. How to cache JSON data from http call to optimize performance?
Try some solution but not working
$http.get(url, { cache: true}).success(...);
Any better solution to this?
After next(Route) to other page, come back it still call back the link. How to cache JSON data from http call to optimize performance?
Try some solution but not working
$http.get(url, { cache: true}).success(...);
Any better solution to this?
On
You can also use angular-data directive for caching. It allows you to specify where caching : local storage / session / memory, and you can set the time you want to keep your requests in cache.
http://angular-data.pseudobry.com/documentation/guide/angular-cache/index
To initialize the cache, add this code in a app.run() function :
DSCacheFactory('defaultCache', {
maxAge: 900000, // Items added to this cache expire after 15 minutes.
cacheFlushInterval: 6000000, // This cache will clear itself every hour.
deleteOnExpire: 'aggressive', // Items will be deleted from this cache right when they expire.
storageMode:'memory' // [default: memory] sessionStorage, localStorage
});
$http.defaults.cache = DSCacheFactory.get('defaultCache');
And then use it in your code like you did :
$http.get(url, { cache: true}).success(...);
On
I recommend to you download angular-cache! It is a very useful replacement for Angular's $cacheFactory
Inside a .run() block, define your cache:
.run(function (DSCacheFactory) {
DSCacheFactory("dataCache", {
storageMode: "localStorage",
maxAge: 720000, // time in milliseconds
deleteOnExpire: "aggressive"
});
}
Then inside your Service you can manage how to use your data, get it from Cache when it expires, make a new call and refresh data.
(function (){
'use strict';
app.factory('DataService', ['$http','$q','DSCacheFactory',DataService]);
function DataService($http, $q,DSCacheFactory){
self.dataCache= DSCacheFactory.get("dataCache");
self.dataCache.setOptions({
onExpire: function(key,value){
getData()
.then(function(){
console.log("Data Cache was automatically refreshed", new Date());
}, function(){
console.log("Error getting data. Putting expired info again", new Date());
// This line of code will be used if we want to refresh data from cache when it expires
self.dealerListCache.put(key,value);
});
}
});
function getData(){
var deferred = $q.defer(),
cacheKey = "myData",
dataFromHttpCall = self.dataCache.get(cacheKey);
if(dataFromHttpCall){
console.log("Found in cache");
deferred.resolve(dealersList);
} else {
$http.get('/api/dataSource')
.success(function (data) {
console.log("Received data via HTTP");
self.dataCache.put(cacheKey, data);
deferred.resolve(data);
})
.error(function () {
console.log('Error while calling the service');
deferred.reject();
});
}
return deferred.promise;
}
};
})();
That´s all!
Better way is to make
CacheFactoryas :-