Skip to content

Instantly share code, notes, and snippets.

@aaronfrost
Created September 30, 2015 17:38
Show Gist options
  • Save aaronfrost/6d619e648356e996457a to your computer and use it in GitHub Desktop.
Save aaronfrost/6d619e648356e996457a to your computer and use it in GitHub Desktop.
caching service in Angular
angular.module('app').factory('myService', function($q, $http){
var data;
var dataPromise;
return {
getData: getData
}
function getData(){
//If the data is already here, return it in a resolved promise
if(data != undefined) return $q.resolve(data);
//If I am already in the process of getting the data from the server, return the same promise
if(dataPromise != undefined) return dataPromise;
//Otherwise, get the data, and return the promise to the caller
dataPromise = $http.get('yourdataurl').then(function(result){
data = result.data;
dataPromise = undefined;
})
return dataPromise;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment