Closed Sithdown closed 9 years ago
There shouldn't be any delay before using it in factories / controllers / providers. As soon as dependencies are resolved and the service is returned it should be ready to read values. Would you mind providing a snippet on how you manage to get undefined values ?
I am using this structure in some services:
.factory('settingsService', function($rootScope, $log, $localStorage){
var i = {
'audio': {
'enabled': true,
'volume': 1.0,
'speed': 1.0
}
};
var c = {
getSettings: function(){
i = $localStorage.kpAppSettings || i;
if(!$localStorage.hasOwnProperty('kpAppSettings'))
{
$log.debug('kpAppSettings not initialized. Loading defaults...');
$localStorage.kpAppSettings = i;
i = $localStorage.kpAppSettings;
}
$log.debug('settingsService:ready');
$rootScope.$broadcast('settingsService:ready',i);
return i;
}
};
return c;
}
Check this out http://plnkr.co/edit/TDPlG140sgIP5sGOJy2c?p=preview if you can?
First load it tells me it initializes defaults. After a refresh it says it's ready.
Which would be how it should behave, or am I missing something?
Oh, I feel stupid now. It seems you've been my rubberduck; after re-reading the code I saw ngStorage is working well; it just doesn't receive any modification because I assigned it to the wrong variable.
Thank you.
You are most welcome.
A way to know when ngStorage module has effectively loaded localStorage values would be very useful.
I am trying to load some localStorage values as soon as the app loads, but ngStorage isn't ready and returns undefined when looking for a key until some time has passed.
Without a way to know when the library is ready and has loaded the storage, or promises in (as it's asynchronous, if I understood correctly), the library is very unreliable.
Am I doing something wrong? Is there an undocumented way to know the readiness of ngStorage?