我读过关于$cacheFactory的文章,当涉及到$http时,它通过url缓存所有东西。现在,我有一些更复杂的需求:
现在,1-3是容易的,4应该手动启动或放入一些计时器.
当您有无限数量的查询组合时,更复杂的是如何处理搜索。
我知道如何开发所有这些,但我想知道是否已经为AngularJs或一般的javascript和ajax调用提供了经过验证的解决方案。
发布于 2012-10-22 18:06:51
可能需要创建自己的服务才能做到这一点。
类似于(psuedo代码,因为我没有服务器来支持这一切).
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!');
});https://stackoverflow.com/questions/13012216
复制相似问题