Ionic local storage


#1

Hello,
I’m having a problem with Ionic using local storage , when I try to save an array it automatically convert it from an object to a string like shown below :

enter image description here

Can anyone please help me ?
Here is the code I’m using :

angular.module('mainApp')
    .factory('cartFactory', function () {
        var cart = [{
            'title': 'titre2',
            'pic': './img/catalogue/k2.jpg'
        }];
        console.log("Type 1:" , typeof(cart) );
        console.log("Content 1:" , cart);
        window.localStorage.setItem('cart', cart);
        var cart = window.localStorage.getItem('cart');
        console.log("Type 2:" , typeof(cart) );
        console.log("Content 2:" , cart);

        return {
            all: function () {
                return cart;
            },
            get: function (index) {
                return cart[index];
            },
            add: function (product) {
                cart.push(product);
            },
            remove: function (product) {
                var index = cart.indexOf(product);
                cart.splice(index, 1);
            }
        };
    });

Thank you !


#2

use JSON.stringify to set the item and JSON.parse when you get it, so replace:

window.localStorage.setItem('cart', cart);
// and
var cart = window.localStorage.getItem('cart');

by,

window.localStorage.setItem('cart', JSON.stringify(cart));
// and
var cart = JSON.parse(window.localStorage.getItem('cart'));