Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
1  
Are you sure url is exactly the same on both controllers/services? –  Andy Gaskell Aug 10 at 3:52
    
Most possibly your url is not exactly the same as previous one.... You could handle it yourself as well... return cachedPromise || cachedPromise = $http.get(url)... –  PSL Aug 10 at 3:57
    
@AndyGaskell Yes is the same controllers/services –  Ricky Aug 10 at 12:18
    
$http.get('script.js', {cache: $templateCache}); –  Noypi Gilas Sep 12 at 10:33

3 Answers 3

Better way is to make CacheFactory as :-

 var cache = $cacheFactory('myCache');

 var data = cache.get(anyKey);

 if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(anyKey, data);
   });
 } 
share|improve this answer

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(...);
share|improve this answer

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!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.