In My Service-factory I Lookup Up A Large Dataset - I Want To Persist It And Check For Its Existence To Avoid Calling It Again
Solution 1:
You can move the declaration of allNames
outside the return statement of your service, and then check if it's null
before querying the API. That way allNames
serves as a cache for the results of the inner API call.
Also, note that it would be better if you return a promise from getMatchingNames
, otherwise your service always returns a blank array right away, which then gets filled later, after the inner API call is completed. If you do return a promise, you would need to change the way you are setting displayNames
in your inputStarted
event handler:
MedicationMatchingNamesFactory.getMatchingNames.then(function(matches) {
$scope.meds.displayNames = matches;
});
and your service could look like this:
.factory('MedicationMatchingNamesFactory',
['$http', '$q', 'MedicationDisplayNamesFactory',
functionMedicationMatchingNamesFactory($http, $q, MedicationDisplayNamesFactory) {
var allNames = null;
functiongetMatches(inputValue, list){
var matches = [];
angular.forEach(list, function(value, key){
if(value.indexOf(inputValue) !== -1){
matches.push(value);
}
});
return matches;
}
return {
getMatchingNames: function(inputValue){
var deferred = $q.defer();
if (allNames !== null) {
deferred.resolve(getMatches(inputValue, allNames));
} else {
MedicationDisplayNamesFactory.getDisplayNames().then(
function(response){
// this is the large dataset - now as array
allNames = response.data.displayTermsList.term;
deferred.resolve(getMatches(inputValue, allNames));
},
function(reason){
deferred.reject(reason);
}
);
}
return deferred.promise;
}
};
}])
Solution 2:
Actually the solution to this problem is very simple: I just went with the sessionStorage
which seems to fit perfectly my needs in this case as I need the big dataset persisted just for this session and it doesn't matter if it's lost on the next one. The goal is to prevent fetching it more than once, that is, more than necessary, as the values inside are not likely to be changed during that session.
Post a Comment for "In My Service-factory I Lookup Up A Large Dataset - I Want To Persist It And Check For Its Existence To Avoid Calling It Again"