My service should get the value asynchronously, but as soon as I get it, I would like to use the cached version of the value.
When two controllers call this service, I expect the first to cache the received value, and the second to use the cached value, but according to the log, I never find the cached value. When this is done, I see a log message that shows the cached value, and then when I follow the angular route to another controller, I cannot see that the service is finding the cached value. Why is it not working according to my expectation **? **
angular.module('myApp.services').factory('Config', function() { var Config = { }; Config.currentYear = function() { if (Config._currentYear) { // sadly, we never execute here console.log("returning cached year"); return Parse.Promise.as(Config._currentYear); } return Parse.Config.get().then(function(config) { console.log("caching year"); Config._currentYear = config.get("currentYear"); return Config._currentYear; }); }; return Config; });
A few notes: (1) I named the cached attribute _currentYear, adding an underscore to avoid clashing with the function name. Not sure if I need to do this. (2) I return a fulfilled promise when the value is cached, so the function always returns a promise ... also not sure if this is necessary, but the figure cannot hurt.
source share