angularjs: how to add caching to resource object?

后端 未结 8 668
栀梦
栀梦 2020-12-02 08:08

To add caching inside http is pretty straight forward. ( by passing cache=true )

http://docs.angularjs.org/api/ng.$http has Cache option.

How do I add simila

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 08:55

    I just came across this really well thought out module called angular-cached-resource that will do the job for you. https://github.com/goodeggs/angular-cached-resource

    It is a drop in replacement for $resource, with added functionality of cache management using localStorage. If your browser doesnt support local storage, you will not get any caching benefit. Here's an example of how you can use it:

    The old way using $resource:

    var Entry = $resource('/entries/:slug', {slug: '@slug'});
    
    var announcement = new Entry();
    announcement.slug = 'announcing-angular-cached-resource';
    announcement.title = 'Announcing Angular Cached Resource';
    announcement.body = 'Here is why Angular Cached Resource is awesome!';
    
    announcement.$save(function() {
      alert('Saved announcement.');
    });
    

    The new way using $cachedResource:

    var Entry = $cachedResource('entries', '/entries/:slug', {slug: '@slug'});
    
    var announcement = new Entry();
    announcement.slug = 'announcing-angular-cached-resource';
    announcement.title = 'Announcing Angular Cached Resource';
    announcement.body = 'Here is why Angular Cached Resource is awesome!';
    
    announcement.$save(function() {
      alert('Saved announcement.');
    });
    

    The only differences in the code are:

    1. Use $cachedResource instead of $resource
    2. Provide a "key" (entriesin the example above) so that you can refer to it even between page refreshes or reloads. These entries persist since out of the box it uses localStorage.

    A detailed tutorial is available here: https://github.com/goodeggs/bites/blob/master/src/documents/open_source/2014-04-24-angular-cached-resource.md

    Also note Angular 2.0 may support something like this out of the box: https://docs.google.com/document/d/1DMacL7iwjSMPP0ytZfugpU4v0PWUK0BT6lhyaVEmlBQ/edit

提交回复
热议问题