Angular cache value service

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.

+5
source share
1 answer

Instead of caching data, why don't you just hide the promise and return it. When you cache data, you set Config._currentYear data only within the success callback, and it is likely that other subsequent calls will be made before the success callback is executed. This way you get the same call again. This can be easily seen when calls made for the same service method are created from different controllers that were created by their presence in the same template. Caching a promise in advance will avoid these problems.

 angular.module('myApp.services').factory('Config', function() { var config; //Just use to save the promise Config.currentYear = function() { /*If there is already a call made before return the promise else make the actual call and store the promise in the variable.*/ return config || config = Parse.Config.get().then(function(config) { return config.get("currentYear"); }); }; }); 
+3
source

Source: https://habr.com/ru/post/1210283/


All Articles