angularjs: how to add caching to resource object?

后端 未结 8 648
栀梦
栀梦 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 09:11

    As the docs state, $resource has built-in support for $cacheFactory. You can pass it in via the cache property of each action:

    cache{boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.

    Example usage:

    app.factory('Todos', function($resource, $cacheFactory) {
        var todosCache = $cacheFactory('Todos');
        return $resource(apiBaseUrl + '/todos/:id', {id: '@id'}, {
            'get': { method:'GET', cache: todosCache},
            'query': { method:'GET', cache: todosCache, isArray:true }
        });
    });
    
    0 讨论(0)
  • 2020-12-02 09:13

    Implementing your own cache in AngularJs is quite easy. Just use $cacheFactory:

    app.factory('myService', function($resource, $cacheFactory) {
       var cache = $cacheFactory('myService');
       var User = $resource('/user/:userId', {userId:'@id'});
    
       return {
          getResource: function(userId) {
             var user = cache.get(userId);
             if (!user) {
                user = User.get({userId:userId});
                cache.put(userId, user);   
             }
             return user;
          }
       };
    });
    
    0 讨论(0)
提交回复
热议问题