1

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?

4
  • 1
    Are you sure url is exactly the same on both controllers/services? Commented Aug 10, 2014 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)... Commented Aug 10, 2014 at 3:57
  • @AndyGaskell Yes is the same controllers/services Commented Aug 10, 2014 at 12:18
  • $http.get('script.js', {cache: $templateCache}); Commented Sep 12, 2014 at 10:33

3 Answers 3

2

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);
   });
 } 
Sign up to request clarification or add additional context in comments.

Comments

1

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(...);

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.