Search code examples
angularjsangularjs-service

Is CacheFactory in angularjs a singleton?


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

Solution

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