我已经阅读了关于$ cacheFactory的内容,当涉及到$ http时,它会通过url缓存所有内容。 现在,我有一些更复杂的需求:
有一些项目列表(用户,文章等)。这个 list从服务器中提取并缓存到缓存中。
当app请求单个项目时,它会进入缓存并且:
2.1。如果存在提供密钥的项目,则从缓存中拉出
2.2。如果缓存列表中没有项目,则它会转到服务器,当服务器获得响应时,将此项目放入缓存列表,以便下次从缓存中提取
当项目保存到数据库时,它会获得一些密钥(自动编号或guid)以及服务器解析响应时:
3.1。如果项目已存在于缓存中,则项目与服务器数据合并/扩展
3.2。如果项目在缓存中不存在,则只需将其添加到列表
应用程序应检查(每10秒钟)列表中是否有新的/更新/删除的项目(由其他用户创建)并刷新(对当前用户工作没有重大影响)
< / LI> 醇>现在,1-3很容易,4应该手动启动或放入一些计时器。
当您拥有无限数量的查询组合时,其他复杂功能是如何处理搜索。
我知道如何开发所有这些,但我想知道是否已经为AngularJs提供了经过验证的解决方案,或者通常是针对javascript和ajax调用。
答案 0 :(得分:9)
可能需要创建自己的服务才能做到这一点。
类似的东西(伪代码,因为我没有服务器支持任何这个)...
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!');
});
答案 1 :(得分:0)
我可以看到,还没有人做过这个,所以我按照$ http和Restangular的标准使用方式自行滚动。如果你想添加它,肯定是分叉请求。