繁体   English   中英

离子本地存储

[英]Ionic local storage

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

在此处输入图片说明

谁能帮帮我吗 ? 这是我正在使用的代码:

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

谢谢 !

localStorage仅支持字符串,最好的选择是将数组转换为json数组,然后将其读回:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM