离子本地存储

时间:2016-06-21 13:33:41

标签: javascript angularjs ionic-framework

我在使用本地存储时遇到Ionic问题,当我尝试保存数组时,会自动将其从对象转换为字符串,如下所示:

enter image description here

任何人都可以帮助我吗? 以下是我使用的代码:

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);
            }
        };
    });

谢谢!

1 个答案:

答案 0 :(得分:2)

localStorage只支持字符串,最好的办法是将数组转换为json数组,然后再读回来:

localStorage.setItem("cart", JSON.stringify(cart));

//...
var cart = JSON.parse(localStorage.getItem("cart"));