Created
September 30, 2015 17:38
-
-
Save aaronfrost/6d619e648356e996457a to your computer and use it in GitHub Desktop.
caching service in Angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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