【问题标题】:Ionic local storage离子本地存储
【发布时间】:2016-06-21 21:39:34
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: javascript angularjs ionic-framework


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!就是这么简单
    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2016-03-05
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多