Angular: Caching API responses in Restangular

Updated . Posted . 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.

Last edit
Deleted user #3651
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2014-11-14 10:35)