Javascript AngularJS高级缓存技术
我读过关于$cacheFactory的文章,当涉及到$http时,它会通过url缓存所有内容。 现在,我有一些更复杂的需求:Javascript AngularJS高级缓存技术,javascript,caching,angularjs,Javascript,Caching,Angularjs,我读过关于$cacheFactory的文章,当涉及到$http时,它会通过url缓存所有内容。 现在,我有一些更复杂的需求: 有一个某种项目(用户、文章等)的列表。这 列表从服务器中提取并缓存到缓存中 当应用程序请求单个项目时,它将进入缓存并: 2.1。如果存在具有提供的密钥的项,它将从缓存中提取 2.2。如果缓存列表中不存在该项,它将转到服务器,当从服务器获取响应时,它会将该项放到缓存列表中,以便下次从缓存中提取该项 当项目保存到数据库时,它会获取一些密钥(自动编号或guid),当服务器解析响
我知道如何开发所有这些,但我想知道是否已经有针对AngularJs或javascript和ajax调用的经验证的解决方案。可能需要创建自己的服务来实现这一点 类似于(psuedo代码,因为我没有服务器来备份这些东西)
据我所见,还没有人做过这个,所以我按照$http和restanglar的标准用法推出了自己的。如果你想增加的话,一定要用叉子拉
您可以让服务使用angulars$interval指令,允许您使用$scope,而不是希望它被拾取
app.factory('andrejsSuperAwesomeService', ['$cacheFactory', '$http', function($cacheFactory, $http) {
//get your cache ready.
var userCache = $cacheFactory('users');
// start an interval to check for data.
// TODO: add a public function to turn this on and off.
setInterval(function(){
//check for changes to the data.
$http.get('/Get/New/User/Changes')
.success(function(changes) {
if(!changes) return;
//we'll assume we get some collection of changes back,
// with some change type and the user data.
for(var i = 0; i < changes.length; i++) {
var change = changes[i];
switch(change.changeType) {
case 'delete':
// okay just remove the deleted ones.
userCache.remove(change.user.id);
break;
case 'addUpdate':
// if it's added or updated, let's just
// remove and re-add it, because we can't know what
// we already have or don't have.
userCache.remove(change.user.id);
userCache.put(chnage.user.id, change.user);
break;
}
}
});
}, 10000); // every 10 secs
return {
users: {
//a function to get a user.
get: function(userId, callback) {
var user = userCache.get(userId);
if(!user) {
//the user is not in the cache so let's get it.
$http.get('/Uri/To/Get/A/User?userId=' + userId)
.success(function(data) {
//great, put it in the cache and callback.
userCache.put(userId, data);
if(callback) callback(data);
});
} else {
//we already have the user, callback.
if(callback) callback(data);
}
}
}
};
});
andrejsSuperAwesomeService.users.get(12345, function(user) {
//do something with user here.
alert(user.name + ' is a naughty user!');
});