Il web storage può essere usato in AngularJS per creare un sistema di caching al fine di evitare di effettuare troppe chiamate alle API.
Possiamo definire il web storage come servizio:
angular.module('MyApp').factory('Storage', function() {
return {
type: sessionStorage,
save: function(item, value) {
this.type.setItem(item, value);
},
read: function(item) {
return this.type.getItem(item);
},
remove: function(item) {
this.type.removeItem(item);
},
hasItem: function(item) {
return (this.read(item) !== null);
},
empty: function() {
this.type.clear();
},
items: function() {
return this.type.length;
},
saveAsJSON: function(item, value) {
this.save(item, JSON.stringify(value));
},
readAsJSON: function(item) {
var value = this.read(item);
return JSON.parse(value);
}
};
});
Quindi possiamo usarlo in questo modo:
angular.module('MyApp').controller('TimeLineCtrl', ['$scope', 'Twitter', 'Storage', function($scope, Twitter, Storage) {
$scope.latestTweets = {};
if(!Storage.hasItem('twitter-app-timeline')) { // Cache vuota
Twitter.getTweets('/status/timeline', {}, function(tweets) {
$scope.latestTweets = data.tweets;
Storage.saveAsJSON('twitter-app-timeline', data.tweets);
});
} else {
// Leggiamo dalla cache
$scope.latestTweets = Storage.readAsJSON('twitter-app-timeline');
}
}]);