Ricky
Ricky

Reputation: 11

AngularJS $http.get cache not working

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?

Upvotes: 1

Views: 1890

Answers (3)

opellon
opellon

Reputation: 1

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!

Upvotes: 0

benek
benek

Reputation: 2178

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

Upvotes: 1

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

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);
   });
 } 

Upvotes: 2

Related Questions