Is CacheFactory in angularjs a singleton?

笑着哭i 提交于 2019-11-27 02:31:29

问题


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?

This is my service as an example:

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

Then in my controller:

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

回答1:


$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;
});

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.

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


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.



来源:https://stackoverflow.com/questions/15583403/is-cachefactory-in-angularjs-a-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!