angularjs 中的 CacheFactory 是单例吗? [英] Is CacheFactory in angularjs a singleton?

查看:23
本文介绍了angularjs 中的 CacheFactory 是单例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 CacheFactory 创建了一个服务.我期待它是一个单身人士.我将它注入我的控制器,它在控制器的范围内工作正常.但是,一旦我转到具有不同范围的不同页面,我似乎没有在不同范围内存储在同一控制器中的缓存中的值.CacheFactory 的行为不应该是一个单例,在我注入 CacheService 的任何地方都有相同的缓存对象吗?

I've created a service using the CacheFactory. I was expecting it to be a singleton. I inject it into my controller and it works fine within the scope of the controller. But once I go to a different page with a different scope, I don't seem to have the values in the cache that I stored in the same controller in a different scope. Shouldn't the behavior of the CacheFactory be a singleton where I have those same cached objects everywhere I inject the CacheService?

以我的服务为例:

angular.module('MyService', []).factory('CacheService', function($cacheFactory) {
        return $cacheFactory('cacheService', {
            capacity: 3 // optional - turns the cache into LRU cache
        })
    });

然后在我的控制器中:

function MyController($scope, CacheService) {
   var results= CacheService.get('storedvalue');
   if(!results){
       CacheService.put('storedvalue', results);
      alert('results not stored');
   }
   else
      alert('results stored');
}

推荐答案

$cacheFactory 实际上不是您想要使用的服务 - 它是您用来创建 要使用的单例服务.观察你的代码,它似乎应该可以工作.但是我继续创建了一个演示来证明它确实如此.这是服务:

$cacheFactory is actually not the service you want to use - it's a factory that you use to create the singleton service you want to use. Eyeballing your code, it seems like it should work. But I went ahead and created a demo to prove that it does. Here's the service:

.factory('CacheService', function($cacheFactory) {
   var cache = $cacheFactory('cacheService', {
     capacity: 3 // optional - turns the cache into LRU cache
   });

   return cache;
});

在这个例子中,CacheService 具有使用$cacheFactory创建的本地缓存的单例,这是我们从服务返回的.我们可以将它注入到我们想要的任何控制器中,它总是会返回相同的值.

In this example, CacheService is the singleton that has a local cache created with $cacheFactory, which is what we return from the service. We can inject this into any controller we want and it will always return the same values.

这是一个有效的 Plunker:http://plnkr.co/edit/loKWGms1lMCnmiWa1QA7?p=preview

Here's a working Plunker: http://plnkr.co/edit/loKWGms1lMCnmiWa1QA7?p=preview

如果由于某种原因您的帖子不包含破坏您代码的内容,请随时更新我的​​ Plunker 以破坏它,我们可以从那里开始.

If for some reason your post doesn't contain what broke your code, please feel free to update my Plunker to break it and we can go from there.

这篇关于angularjs 中的 CacheFactory 是单例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆