I'm keeping track of the current culture using localisation cookie. I want to load all the messages for the currently selected culture when the application starts and keep them in localStorage
together with information about their culture, then refresh them only when the selected culture changes (when the value of 'CurrentCulture'
in localStorage
is different than the one in the cookie).
In my controller, I set
$scope.messages = localisationService.messages(localisationMessagesUrl, currentCulture);
In localisationService
, I have
app.service("localisationService", function ($q, $http, localStorageService) {
var getCachedMessagesForLanguage = function (localisationMessagesUrl, language) {
console.log('getCachedMessagesForLanguage');
var messages = localStorageService.get('Localisation');
if (!messages || language !== localStorageService.get('Language')) {
getLocalisationsFromServer(localisationMessagesUrl).then(function (serverMessages) {
localStorageService.add('Localisation', messages);
localStorageService.add('Language', language);
});
}
return localStorageService.get('Localisation')
}
function getLocalisationsFromServer(localisationMessagesUrl) {
return $q(function (resolve) {
$http.get(localisationMessagesUrl)
.then(function (response) {
resolve(response.data);
});
});
}
return {
messages: function (localisationMessagesUrl, language) {
return getCachedMessagesForLanguage(localisationMessagesUrl, language);
}
};
});
getCachedMessagesForLanguage
returns undefined
before getLocalisationsFromServer
finishes, so on the first load I have no messages. If I refresh the page then I get them correctly. How can I solve this?
make getCachedMessagesForLanguage
return a deferred.promise
You can then do ..
getCachedMessagesForLanguage(localisationMessagesUrl,
language).then(function(Localisation) {
return getLocalisationsFromServer(localisationMessagesUrl)
}).then(function(responseFromGetLocalisationsFromServer) {
// do your thing here
})