预填充 AngularJS $resource缓存



我之前的问题强调了我的服务中的缓存可能性。

ngResource 的文档(撰写本文时为v1.3.0-build.2417(快照))显示了一个cache标志。

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

(从 2+ 个端点提供相同的项目是完全合理的。 例如,如果任务 5 是项目 99 的一部分,您可以在/task/5上提供任务,并在/projects/99/tasks上作为集合的一部分)

我试过这个,但它非常丑陋:

// 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

在控制器中:

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

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

您可以将缓存值手动放入缓存工厂。 注入$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缓存。 您也可以将其设置为自定义缓存工厂实例。 在这种情况下,您只需将值放入自定义缓存即可。

最新更新