Using localStorage as an $http cache

1,723 views
Skip to first unread message

Marc Cawood

unread,
Jan 2, 2013, 9:24:13 AM1/2/13
to ang...@googlegroups.com
Sometimes it would be nice to cache all $htto calls to localStorage. This could make sense for very static data sources or to reduce the cost of using paid http services (like Google APIs).

I've taken a stab at implementing a cache by overriding the get() and put() methods of the $cacheFactory here:

To use, just include the 'Cacher' service in your code (and as a dependency of your module/application). Next inject and pass CacheLocal as the cache option to all your $http calls.
$http.get(url, {cache: CacheLocal});

The first time the URL is requested it will be fetched via HTTP, thereafter fetched from localStorage.

Feedback welcome as well as better ways of doing this - perhaps via http interceptors?

Marc Cawood

unread,
Jan 2, 2013, 1:10:46 PM1/2/13
to ang...@googlegroups.com
PS: It seems AngularJS does not support the cache option for $http.jsonp() - Where can one submit suggestions?

Michael Bielski

unread,
Jan 3, 2013, 10:43:45 AM1/3/13
to ang...@googlegroups.com
I see methods for clearing individual items and the cache as a whole, but how are you determining when to call them? What caching rules are you using? LocalStorage is limited to somewhere 5mb per domain in the browser, and a busy page could reach that pretty easily. Once the cache is full, how would you then determine what gets flushed and replaced?

I'm just having a hard time wrapping my head around caching data in a RESTful environment. I think I can see a use for it (enabling an offline mode) but I still just can't get it to settle into my head.

Marc J. Cawood

unread,
Jan 4, 2013, 5:15:38 AM1/4/13
to ang...@googlegroups.com
On 3 January 2013 16:43, Michael Bielski <michael...@yahoo.com> wrote:
I see methods for clearing individual items and the cache as a whole, but how are you determining when to call them? What caching rules are you using?
The scenario is that the application caches certain $http calls with no expiration rules. The user can click a button/link which clears the entire cache or a refresh button to clear and reload a specific item. It's mainly for development actually where it does not always make sense to do 10+ AJAX requests each time the developer refreshes the page.

Michael Bielski

unread,
Jan 4, 2013, 10:35:56 AM1/4/13
to ang...@googlegroups.com
Hmm... interesting... I think I can get behind that.
Reply all
Reply to author
Forward
0 new messages