我是 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 参数的唯一性为您进行缓存。
关于javascript - 在 Angular $cacheFactory 中缓存多个数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27602993/