2014-03-12 51 views
1

我的previous question在我的服务中突出显示了缓存的可能性。

documentation for ngResourcev1.3.0-build.2417(快照)在撰写本文时)显示了一个cache标志。

但是,只有在第一次调用service.get(id)后才会填充缓存。我希望能够使用从其他地方检索到的项目预先填充资源缓存

(从2+端点获得相同的项目是完全合理的,例如,您可以在/task/5并且在/projects/99/tasks集合的一部分,如果任务5项目99)

我已经试过这种的一部分,但它是非常难看:

// return the API in the project service 
return { 
     project: null, // my own hand-rolled cache 

     get: function (id) { 

      // check cache 
      if (this.project != null && this.project.id == id) { 
       console.log("Returning CACHED project", this.project); 
       var future = $q.defer(); 
       future.resolve(this.project); 
       // UGLY: for consistent access in the controller 
       future.$promise = future.promise; 
       return future; 
      } else { 
       return Projects.get({ 
        id: id 
       }); 
      } 
     }, // etc 

和Controller:

$q.when(projectService.get($routeParams.id).$promise).then(function(project) { 
    // etc 

如何使用AngularJS成语预先填充缓存?

回答

0

您可以手动将缓存值放入缓存工厂。注入$ cacheFactory,获取http缓存,并将该对象放入缓存中,其中键为资源的路径。

例如:

var task = { 
    // ... task object here ... 
}; 

var httpCache = $cacheFactory.get('$http'); 
httpCache.put('/projects/99/tasks/5', task); 
httpCache.put('/task/5', task); 

有一点需要注意,如果你在你的资源设置为true缓存标志,它会默认使用$ HTTP缓存。您也可以将其设置为自定义的cacheFactory实例。在这种情况下,您只需将该值添加到自定义缓存中即可。