Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js - cache a rootScope param and it's value

Hey how do i cache for x time this simple object that i set via $http ( $rootScope.config.app_genres)?

 $http.get($rootScope.config.app_ws+'get/genres',{},{cache:true}).success(function(response) {
    $rootScope.config.app_genres =  response;
  });

i just would like to cache it to not repeat everytime the http request

like image 250
itsme Avatar asked Feb 09 '14 14:02

itsme


2 Answers

As stated in $http documentation, you can provide your own cache object instance through the cache configuration option.

Here's a $cacheFactory where I override the put method so that the cache gets cleared after TIMEOUT. Note that this only works for one URL. I'll leave making this timer cache object generic as an exercise for you.

function Ctrl($scope, $http, $cacheFactory, $timeout) {
  var timedCache = $cacheFactory('myCache'),
      TIMEOUT = 5000,
      cacheTimer = null;

  timedCache._put = timedCache.put;
  timedCache.put = function (key, val) {
    console.log('caching', key);

    $timeout.cancel(cacheTimer);
    cacheTimer = $timeout(function () {
      console.log('clearing cache for', key);
      timedCache.remove(key);
    }, TIMEOUT, false);

    timedCache._put(key, val);
  };

  $scope.request = function () {
    $http.get('/echo/json', {
      cache: timedCache
    })
    .success(function (data) {
      console.log('received', data);
    });
  };
}

Here's the fiddle with this working: http://jsfiddle.net/sirhc/jvLPX/

like image 200
sirhc Avatar answered Sep 21 '22 04:09

sirhc


H i , ( hoping Angular has something built in, that others may add but )

I guess we could assign it to a new variable

$rootScope.dataCache = $rootScope.data;

$rootScope.cacheTimer = 50000; 

Your websites application always reading from $rootScope.dataCache and a routine to check and/or auto update when CacheTimer had elapsed, to recall the server side and re assign.

?

like image 36
Rob Sedgwick Avatar answered Sep 22 '22 04:09

Rob Sedgwick