Caching multiple data in Angular $ cacheFactory?
I am new to angular and I need to cache data for better performance. I am using Angular's $ cacheFactory for this .
When I try
myApp.factory('myCache', function($cacheFactory) {
return $cacheFactory('myData');
});
FROM
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);
}
);
}
}
This works fine, but it only caches one dataset, since I want to cache multiple datasets that I am using
myApp.factory('myCache', function($cacheFactory) {
return {
get : function(cacheKey){
return $cacheFactory(cachekey);
}
}
});
So, if I go to another page, I can cache another set of data, for example
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);
}
);
}
}
and etc.
However, in the latter case, although it gives no error, no data is returned and no ajax call is made to cache the data.
How can I fix this? And cache multiple datasets with $ cacheFactory?
source to share
If your url is unique for the data you are requesting, you must use the inline cache internally $http
:
$http.get('http://www.example.com/path/to/api/endpoint', { cache: true }).success(...
The cache will be based on the uniqueness of the URL parameter cacheProvider
for you.
Below is the documentation for this function.
source to share