【问题标题】:Pre-populating the AngularJS $resource cache预填充 AngularJS $resource 缓存
【发布时间】:2014-10-17 02:22:24
【问题描述】:

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

documentation for ngResource(在撰写本文时v1.3.0-build.2417(快照))显示cache 标志。

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

(从 2+ 个端点提供相同的项目是完全合理的。例如,如果任务 5 是项目的一部分,您可以在 /task/5 和作为集合的一部分在 /projects/99/tasks 获取任务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

在控制器中:

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

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

【问题讨论】:

    标签: angularjs


    【解决方案1】:

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

    例如:

    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 实例。在这种情况下,您只需将值放入自定义缓存即可。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2020-05-09
      • 2013-06-08
      • 2017-06-16
      • 2015-03-27
      • 1970-01-01
      相关资源
      最近更新 更多