Reputation: 12660
I am trying to write a service in Angular that will cache data to localStorage, without much success! I need your help. I have several "lookup" datatypes that don't change very frequently, such as broker codes and airline codes.
I remember reading in one of my (many!) tech books that it is possible to wrap a promise around any data type, and I am taking this approach in writing my service. Essentially, I want to return the value from localStorage if it exists, then return immediately with a resolved promise. Or, in the case that it doesn't exist, I want to $http.get() it and return the promise returned from this call.
My pseudocode would look like this:
angular.module('myApp')
.service("lookupDataService", function() {
this.brokers = function() {
var cachedBrokers = localStorage.getItem("brokers");
if (!cachedBrokers) {
$http.get('/api/brokers')
.success(function(data) {
localStorage.setItem("brokers", data);
// return promise
});
} else {
var deferred = $q.defer();
deferred.resolve();
// shoehorn the data from localStorage
return deferred;
}
}
})
Is this approach sound? How do I return a promise and the data to the calling behaviour?
EDIT
I realised I wasn't doing my dependency injection correctly. I have modified my pseudocode to look like this:
angular.module('myApp')
.service("lookupDataService", ['$q','$http', function($q, $http) {
this.brokers = function() {
var cachedBrokers = localStorage.getItem("brokers");
if (!cachedBrokers) {
return $http.get('/api/brokers')
.success(function(data) {
localStorage.setItem("brokers", data);
}
);
} else {
return $q.when(cachedBrokers);
}
}}]
)
It occurred to me that my method wasn't returning a promise until the internal promise was resolved. I think. Head-scratching moment.
M
Upvotes: 1
Views: 2450
Reputation: 552
I would look into NGStorage,http://ngmodules.org/modules/ngStorage.
<script>
angular.module('app', [
'ngStorage'
]).
controller('Ctrl', function(
$scope,
$localStorage
){
$scope.$storage = $localStorage.$default({
x: 42
});
});
</script>
Upvotes: 1