javascript - 在 Angular $cacheFactory 中缓存多个数据?

标签 javascript angularjs caching

我是 Angular 的新手,我需要缓存数据以提高性能。为此,我使用 $cacheFactory通过 Angular。

当我尝试时,

myApp.factory('myCache', function($cacheFactory) {
 return $cacheFactory('myData');
});

myApp.controller('MyMain', ['$scope', '$http', 'myCache',
 function ($scope, $http, myCache) {
   var cache = myCache.get('myData');
   if (cache) {
     $scope.variable = cache;
   }
   else {
     $http.get('http://www.example.com/path/to/api/endpoint')
       .success(function(data) {
         $scope.variable = data;

         myCache.put('myData', data);
       }
    );
  }
}

这很好用,但它只缓存了一组数据,因为我想缓存我使用的多组数据

myApp.factory('myCache', function($cacheFactory) {
 return {
  get : function(cacheKey){
    return $cacheFactory(cachekey);
     }
   }
});

所以如果我转到另一个页面,我可以像这样缓存另一组数据,

myApp.controller('MyMain', ['$scope', '$http', 'myCache',
 function ($scope, $http, myCache) {
   var cache = myCache.get('myData2');
   if (cache) {
     $scope.variable = cache;
   }
   else {
     $http.get('http://www.example.com/path/to/api/endpoint')
       .success(function(data) {
         $scope.variable = data;

         myCache.put('myData2', data);
       }
    );
  }
}

等等

然而,在后一种方式中,虽然它没有给出任何错误,但没有返回数据,也没有进行 ajax 调用来缓存数据。

我该如何解决这个问题?并使用$cacheFactory缓存多组数据?

最佳答案

如果您的 URL 对于您正在查询的数据是唯一的,那么您应该使用 $http 中的内置缓存:

$http.get('http://www.example.com/path/to/api/endpoint', { cache: true }).success(...

这将根据 cacheProvider 中 URL 参数的唯一性为您进行缓存。

Here is the documentation对于此功能。

关于javascript - 在 Angular $cacheFactory 中缓存多个数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27602993/

相关文章:

java - 在 Java 客户端中使用缓存控制 header

asp.net - 仅为匿名用户缓存 ASP.NET 页面

javascript - 是否可以使用标记模板文字并将模板文字保存为常量?

javascript - !Array.<string>= 是什么意思?

JavaScript 对象?

html - angular ng-repeat隐藏了div的样式

http - 什么优先 : the ETag or Last-Modified HTTP header?

javascript - 使用 .getElementsByClassName() 的 Typescript 返回类型

javascript - 获取 Javascript 对象属性名称

Javascript 查找缺失的选择值