Is CacheFactory in angularjs a singleton?

前端 未结 1 762
刺人心
刺人心 2020-12-09 13:56

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. Bu

相关标签:
1条回答
  • 2020-12-09 14:28

    $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.

    0 讨论(0)
提交回复
热议问题