Hi, do you know how to do caching in Ionic/Angular that would clear itself after some time. the Angular caching doesn’t seem to have the option of clearing itself. so was wondering if there is anything else? thank you
I had the same question some time ago. I created a service for this purpose and saved the data to $cacheFactory with a timestamp. For the timestamp I used Date.now() and compared it on every request.
thank you, would you mind sharing some of your code?
No. But I’m not sure if it fits you needs. I only have one host so its static. Insert a variable if you want to call it dynamicly.
.factory('$apiService', function($http, $ionicLoading, $ionicPopup, $cacheFactory, $rootScope) {
var cache = $cacheFactory('httpgetcache');
var cacheTime = $cacheFactory('httptimecache');
return {
clearCache: function(path)
{
return cache.remove(path + '?');
},
request: function (path, type, data, cacheControl, animation, onsuccess, onfail, showErrors)
{
type = type || 'GET';
data = data || {};
cacheControl = cacheControl || false;
animation = animation || false;
onsuccess = onsuccess || function() {};
onfail = onfail || function() {};
showErrors = showErrors || true;
if(type == 'GET')
{
path = path + '?';
for (var key in data) {
path += key + "=" + data[key] + "&";
}
if(cacheControl && cache.get(path) && Date.now() - cacheTime.get(path) < 120000)
{
onsuccess(cache.get(path));
return true;
}
}
if(animation)
{
$ionicLoading.show();
}
$http({
method : type,
url : 'http://whatever.com/' + path,
data : data
})
.success(function(data) {
if(data.error)
{
if(data.error == 'ERROR_AUTH')
{
localStorage.removeItem('apikey');
document.location.href = '#/login';
}
$ionicLoading.hide();
if(showErrors)
{
$ionicPopup.alert({
title: $rootScope.LANG_ERROR,
template: $rootScope['LANG_' + data.error]
});
}
onfail(data.error);
} else {
$ionicLoading.hide();
if(type == 'GET')
{
cache.put(path, data);
cacheTime.put(path, Date.now());
}
onsuccess(data);
}
})
.error(function(){
$ionicLoading.hide();
if(showErrors)
{
$ionicPopup.alert({
title: $rootScope.LANG_ERROR,
template: $rootScope.LANG_ERROR_NETWORK
});
}
onfail('ERROR_NETWORK');
});
}
}
})
1 Like
thank you a lot. I might get an idea of how to implement it.
1 Like