Angular Service Restangular Caching

天涯浪子 提交于 2019-12-03 12:38:30

问题


Are there scenarios where an angular service will cache Restangular/$http calls without being explicitly told to do so? For example I have a service doing something like this:

    function getSomeThings(){
        return Restangular.one('things').get().then(function (thing) {
            return thing;
        });
    }

This service gets called every time a page refreshes (it's in the UI-router route resolve). Is there any chance that this call WON'T be made every time, but will be cached by Angular somehow, without explicitly being told to do so?

I am familiar with caching explicitly like so:

RestangularProvider.setDefaultHttpFields({cache: true});

This is NOT the intent. My question is whether angular services have some innate caching logic, and if so, how to override it.


回答1:


By default Restangular doesn't implement any caching strategies or scenarios, you will need to build your owns. As far as i know, those are what you can do with cache when working with Restangular :

  1. You can cache everything as you said but you might find yourself working with stale data, so be careful with that :

    RestangularProvider.setDefaultHttpFields({cache: true});
    
  2. You can cache response for single requests like :

    function getSomeThings(){
        Restangular.one('thing', 123).withHttpConfig({ cache: true}).get().then(function (thing) {
            return thing;
        });
    }
    
  3. You can involve a custom $cacheFactory instance to expire or invalidate cached responses when necessary by invoking this : $cacheFactory.get('$http').removeAll()

  4. You can roll in your own cache interface instead of setting true to the cache. This is a factory example that I'm using to remove all cached data whenever I'm sending a create, update or delete request :

        .factory('HTTPCache', ['Restangular', '$cacheFactory', 
          function(Restangular, $cacheFactory) {
           var service = {};
           var cache;
    
           // Creates the cache
           service.init = function() {
               cache = $cacheFactory('http');
               Restangular.setDefaultHttpFields({cache: cache});
    
               Restangular.setResponseInterceptor(function(response, operation) {
                   if (operation === 'put' || operation === 'post' || operation === 'remove') {
                       cache.removeAll();
                   }
                   return response;
               })
           }
    
           return service;
    
        }])
    


来源:https://stackoverflow.com/questions/31823091/angular-service-restangular-caching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!