I am attempting to use angular-cache in the app.config section of my angular application as shown in this JSFiddle - http://jsfiddle.net/0b1jgwoj/
.config(function (componentFactoryProvider, Config, RestangularProvider, DSCacheFactory, $q) {
componentFactoryProvider.setViewPath(function (componentSnakeName, componentName) {
return 'components/' + componentSnakeName + '/' + componentSnakeName + '.html';
})
RestangularProvider.setBaseUrl(Config.API.path);
RestangularProvider.setRequestSuffix('.json');
var appCache = DSCacheFactory('appCache', {
maxAge: 3600000,
deleteOnExpire: 'aggressive',
storageMode: 'localStorage', // This cache will sync itself with `localStorage`.
onExpire: function (key, value) {
//Todo: implement logic to get data from server be it a collection or single object
}
});
//Intercept the Get Request and check for value in cache. If found cancel Get Request, if not continue get Request.
RestangularProvider.addFullRequestInterceptor(function (element, operation, what, url, headers, params, httpConfig) {
if(operation === 'get') {
debugger;
//Check the cache to see if the resource is already cached
var data = appCache.get(url);
//If cache object does exist, return it
if (data !== undefined) {
angular.extend(element, data);
var defer = $q.defer();
httpConfig.timeOut = defer.promise;
defer.resolve();
return {
headers: headers,
params: params,
element: element,
httpConfig: httpConfig
};
}
}
});
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response) {
//Cache the response from a get method
if(operation === 'get') {
debugger;
appCache.remove(url);
appCache.put(url, data);
}
//Unvalidate the cache when a 'put', 'post' and 'delete' is performed to update the cached version.
if (operation === 'put' || operation === 'post' || operation === 'delete') {
appCache.destroy();
}
return response;
});
})
Two errors arise (1) $q is not defined even though I have put it inside the DI list (2) DSCacheFactory is returning an Unknown Provider Error
Any ideas on how to solve these problems as it is important that this logic remains in .config() section since the restangular 'addFullRequestInterceptor' doesn't cancel the request in any other services but only the config section.
Thanks