AngularJS $ http.get缓存不起作用

时间:2014-08-10 03:35:47

标签: angularjs angularjs-http angular-cache

在下一个(路线)到其他页面后,回来它仍然回叫链接。 如何从http调用缓存JSON数据以优化性能?

尝试一些解决方案,但不能正常工作

  

$ http.get(url,{cache:true})。success(...);

对此更好的解决方案?

3 个答案:

答案 0 :(得分:2)

更好的方法是将CacheFactory设为: -

 var cache = $cacheFactory('myCache');

 var data = cache.get(anyKey);

 if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(anyKey, data);
   });
 } 

答案 1 :(得分:1)

您还可以使用angular-data指令进行缓存。它允许您指定缓存的位置:本地存储/会话/内存,您可以设置将请求保留在缓存中的时间。

http://angular-data.pseudobry.com/documentation/guide/angular-cache/index

要初始化缓存,请在app.run()函数中添加此代码:

     DSCacheFactory('defaultCache', {
        maxAge: 900000, // Items added to this cache expire after 15 minutes.
        cacheFlushInterval: 6000000, // This cache will clear itself every hour.
        deleteOnExpire: 'aggressive', // Items will be deleted from this cache right when they expire.
        storageMode:'memory' // [default: memory] sessionStorage, localStorage
    });

    $http.defaults.cache = DSCacheFactory.get('defaultCache');

然后像你一样在你的代码中使用它:

$http.get(url, { cache: true}).success(...);

答案 2 :(得分:0)

我建议您下载angular-cache!它是Angular的$ cacheFactory

的一个非常有用的替代品

在.run()块中,定义缓存:

.run(function (DSCacheFactory) {
    DSCacheFactory("dataCache", { 
        storageMode: "localStorage",
        maxAge: 720000, // time in milliseconds
        deleteOnExpire: "aggressive"
    });
}

然后在您的服务中,您可以管理如何使用您的数据,在缓存过期时从缓存中获取数据,进行新的调用并刷新数据。

(function (){
'use strict';

app.factory('DataService', ['$http','$q','DSCacheFactory',DataService]);

function DataService($http, $q,DSCacheFactory){
    self.dataCache= DSCacheFactory.get("dataCache");

self.dataCache.setOptions({
        onExpire: function(key,value){
            getData()
                .then(function(){
                    console.log("Data Cache was automatically refreshed", new Date());
                }, function(){
                    console.log("Error getting data. Putting expired info again", new Date());
                    // This line of code will be used if we want to refresh data from cache when it expires
                    self.dealerListCache.put(key,value);
                });
        }
    });

function getData(){
        var deferred = $q.defer(),
            cacheKey = "myData",
            dataFromHttpCall = self.dataCache.get(cacheKey);

        if(dataFromHttpCall){
            console.log("Found in cache");
            deferred.resolve(dealersList);
        } else {
            $http.get('/api/dataSource')
                .success(function (data) {
                    console.log("Received data via HTTP");
                    self.dataCache.put(cacheKey, data);
                    deferred.resolve(data);
                })
                .error(function () {
                    console.log('Error while calling the service');
                    deferred.reject();
                });
        }

        return deferred.promise;
    }
};

})();

这就是全部!