Angular: Caching API responses in Restangular

Posted Over 9 years ago. Visible to the public.

Restangular can make use of $http's built-in response cache.

# Cache response for single request
Restangular.one('accounts', 123).withHttpConfig({ cache: true }).get();

# Cache responses for all requests (be careful with that, you might work with stale data)
RestangularProvider.setDefaultHttpFields({ cache: true });

To invalidate cached responses e.g. on a state change in UI Router, you can do

@app.run ['$rootScope', '$cacheFactory', ($rootScope, $cacheFactory) ->
  $rootScope.$on '$stateChangeSuccess', ->
    $cacheFactory.get('$http').removeAll()
]

Alternative approaches might involve a custom $cacheFactory instance for your Restangular resources where you could expire cached responses whenever nescessary.

Thomas Klemm
Last edit
Over 9 years ago
Thomas Klemm
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Klemm to makandra dev (2014-11-14 10:35)