AngularJS $http cache expiration time

后端 未结 4 933
你的背包
你的背包 2021-02-13 12:50

Can you set an expiration time for Angular\'s $http default caching system ? I would like that an URL stays in the cache for 1 minute, so that any requests made to it after 1 mi

4条回答
  •  被撕碎了的回忆
    2021-02-13 13:27

    Another Solution:

    Use $httpProvider to hook the request.

    http_ttl_cache = {}  # save the last cache time
    MyApp.config ['$httpProvider', ($httpProvider) ->
        $httpProvider.interceptors.push ['$cacheFactory', ($cacheFactory) ->
            request: (config) ->
                if config.params and config.params.__cache__
                    config.cache = true
    
                    N = config.params.__cache__
                    delete config.params.__cache__
    
                    if moment() - (http_ttl_cache[config.url] or 0) > 1000 * N     
                        cache = $cacheFactory.get('$http')                            
                        cache.remove(config.url)                                      
                        http_ttl_cache[config.url] = moment()
                return config
        ]
    ]
    

    In your controller:

    # 600 is 600 seconds
    $http.get("/api/books?limit=100", 
              {
                   params: {'__cache__': 600, 'foo': 'bar'}
              }
    )
    

提交回复
热议问题