预填充AngularJS$资源缓存

预填充AngularJS$资源缓存,angularjs,Angularjs,我的服务突出了缓存的可能性 (撰写本文时的v1.3.0-build.2417(快照))显示缓存标志 但是只有在第一次调用service.get(id)之后,才会填充缓存。我希望能够使用从其他地方检索到的项预填充资源缓存 (从2个以上的端点可以使用相同的项目是完全合理的。例如,如果任务5是项目99的一部分,您可以在/task/5上使用任务,并作为集合的一部分在/projects/99/tasks上使用任务) 我试过这个,但它很难看: // return the API in the project

我的服务突出了缓存的可能性

(撰写本文时的v1.3.0-build.2417(快照))显示
缓存
标志

但是只有在第一次调用
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缓存。还可以将其设置为自定义cacheFactory实例。在这种情况下,您只需将该值放入自定义缓存即可