Incorporating dynamic loading of a static resource in AngularJS using Promises is my goal. The challenge lies in having multiple components on the page that may or may not require the same static resource from the server, depending on which are displayed dynamically. Once loaded, the resource can be cached for the duration of the application.
Although I have implemented this mechanism, my proficiency in Angular and Promises is still developing. Therefore, I am seeking validation regarding the effectiveness of my solution/approach.
var data = null;
var deferredLoadData = null;
function loadDataPromise() {
if (deferredLoadData !== null)
return deferredLoadData.promise;
deferredLoadData = $q.defer();
$http.get("data.json").then(function (res) {
data = res.data;
return deferredLoadData.resolve();
}, function (res) {
return deferredLoadData.reject();
});
return deferredLoadData.promise;
}
This approach ensures that only one request is sent, and all subsequent calls to `loadDataPromise()` will receive the initial promise. This method appears to handle requests that are in progress or already completed successfully.
However, I am uncertain whether caching Promises is considered an optimal solution. Is this practice advisable?