Recently, I came across a project in AngularJS that had some structural issues. One of the main problems was related to fetching settings from an API endpoint. There were times when the application tried to access these settings before they were fully loaded, leading to errors showing up as 'undefined.'
To address this issue, I made use of a getter function. The concept behind it was simple - whenever a method wanted to access the settings object, it would first check if the data had been retrieved from the API. If not, it would make a call to fetch the required information.
After spending some time on it, I managed to get it working. However, there was a flaw in this approach. In cases where multiple methods simultaneously accessed the settings (such as during the page load), the API was hit multiple times because the initial request hadn't finished loading the data into the internal _settings
variable yet.
vm._settings = null;
Object.defineProperty(vm,'settings',{get: function(){
if(vm._settings == null){
settings_service.get().$promise.then(function success(response) {
vm._settings = response;
console.log(vm._settings);
console.log("returning in");
return vm._settings;
}, function error(err) {
handle_api_error(ngNotify, err);
});
}
else return vm._settings;
}});
I'm currently stuck on finding a way to make other attempts to execute the getter function wait until the initial call returns and then utilize that result. I am unsure whether I should explore using await, promises, or any other technique. Your assistance on this matter would be greatly appreciated. Thank you.