;(function(){ 'use strict'; function CacheManager( $http, AugmentedDeferredService, CacheFactory ) { // Set up angular cache CacheFactory.createCache('apiCache', { maxAge: 24 * 60 * 60 * 1000, // Items added to this cache expire after 1 day. cacheFlushInterval: 24 * 60 * 60 * 1000, // This cache will clear itself every day. deleteOnExpire: 'aggressive', // Items will be deleted from this cache right when they expire. storageMode: 'localStorage' // This cache will use `localStorage`. }); var apiCache = CacheFactory.get('apiCache'); return { getCachedData: getCachedData }; /** * Get data from cache and simultaneously make service api call to get updated data * @param url - Api url * @param params - Parameters * @returns {IPromise<T>|function(any=): JQueryPromise<T>|function(string=, Object=): JQueryPromise<any>|*|string} */ function getCachedData(url, params) { var result = apiCache.get(url + '/' + params); var defer = AugmentedDeferredService.defer(); // If data in cache return immediately if(result){ defer.resolve(result); } //Also, simultaneously make api call to get updated data $http.get(url, params) .then(function(response){ // Update cache and resolve the promise second time with updated data apiCache.put(url + '/' + params, response); defer.resolve(response); }); return defer.promise; } } CacheManager.$inject = ['$http', 'AugmentedDeferredService', 'CacheFactory']; angular .module('app') .service('CacheManager', CacheManager); })();