Cos'è un servizio in AngularJS? Per spiegarlo implementeremo un carrello e-commerce di base.
Dobbiamo implementare la creazione di un carrello utilizzando il web storage. Quindi ci occorre una struttura per contenere sia la logica del carrello (aggiunta e rimozione dei prodotti, calcolo del totale ecc.) sia un'interfaccia per il web storage stesso.
Cominciamo dal web storage:
var app = angular.module('MyApp', ['ngRoute']);
// Creo il servizio Storage con il metodo .factory()
app.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);
}
};
});
Il servizio Storage
verrà quindi usato nel servizio destinato a gestire direttamente il carrello:
app.factory('Cart', ['Storage', function(Storage) {
return {
count: function() {
var num = 0;
if(Storage.hasItem('ecommerce-cart')) {
var cart = Storage.readAsJSON('ecommerce-cart');
num = cart.items.length;
}
return num;
},
addToCart: function(product) {
if(!Storage.hasItem('ecommerce-cart')) {
var cart = {};
cart.items = [];
cart.items.push(product);
Storage.saveAsJSON('ecommerce-cart', cart);
} else {
var cart = Storage.readAsJSON('ecommerce-cart');
cart.items.push(product);
Storage.saveAsJSON('ecommerce-cart', cart);
}
},
removeProduct: function(title) {
var cart = Storage.readAsJSON('ecommerce-cart');
var items = cart.items;
for(var i = 0; i < items.length; ++i) {
if(items[i].title == title) {
items.splice(i, 1);
break;
}
}
var data = items;
var newCart = {};
newCart.items = data;
Storage.remove('ecommerce-cart');
Storage.saveAsJSON('ecommerce-cart', newCart);
},
getCartTotal: function() {
var cart = Storage.readAsJSON('ecommerce-cart');
var items = cart.items;
var total = 0;
for(var i = 0; i < items.length; ++i) {
var product = items[i];
var price = Number(product.price);
var partial = price;
total += partial;
}
return total;
},
emptyCart: function(callback) {
if(Storage.hasItem('ecommerce-cart')) {
Storage.remove('ecommerce-cart');
callback();
}
},
updateCart: function(newCart) {
Storage.remove('ecommerce-cart');
Storage.saveAsJSON('ecommerce-cart', newCart);
},
getCart: function() {
var cart = Storage.readAsJSON('ecommerce-cart');
var items = cart.items;
return items;
}
};
}]);
Riassumendo: quando la logica della nostra applicazione necessita di un componente riusabile e condivisibile che ne racchiuda una parte, allora quello che possiamo fare è creare un servizio. Nel nostro caso qualsiasi controller può accedere al carrello usando il servizio Cart
.