Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh / invalidate $resource cache in AngularJS

I have a simple User $resource that uses the default $http cache implementation like so:

factory('User', function($resource){
    return $resource(endpoint + '/user/current/:projectId', {},
        {get: 
            {
                cache: true,
                method: 'GET'
            }
        }
    );
})

This works very well, i.e. my server is only called once in my application, then the value is fetched from cache.

But I need to refresh the value from the server after a certain operation. Is there an easy way to do that?

Thanks.

like image 244
Alexandre Bulté Avatar asked Jun 12 '13 07:06

Alexandre Bulté


2 Answers

Keep the boolean and get the $http cache:

var $httpDefaultCache = $cacheFactory.get('$http');

Then you can control it like any another cache made with $cacheFactory, a usage instance provided below:

$httpDefaultCache.remove(key);
// Where key is the relative URL of your resource (eg: /api/user/current/51a9020d91799f1e9b8db12f)
like image 153
Anthonny Avatar answered Oct 24 '22 09:10

Anthonny


Instead of using a boolean argument in the cache property of each action you can pass on a cache instance created with $cacheFactory which you can have more control over (i.e. clear the cache).

Example usage:

app.factory('Todos', function($resource, $cacheFactory) {
    var cache = $cacheFactory('todo');
    return $resource(apiBaseUrl + '/todos/:id', { id: '@id' }, {
        'get': { method: 'GET', cache: cache  },
        'query': { method: 'GET', cache: cache, isArray: true }
    });
});
like image 18
Variant Avatar answered Oct 24 '22 09:10

Variant