javascript - ionic 本地存储

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

谢谢!

最佳答案

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

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

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

关于javascript - ionic 本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37945943/

相关文章:

javascript - 处理ajax成功的PDF结果数据

javascript - 在浏览器中存储多个图像的base64图像数据

AngularJS 错误 : [ng:areq] Argument 'fn' is not a function, 使用 Google Maps SDK 异步加载器获取字符串

ionic-framework - 类型 'iOSExternalAccessory' 上不存在属性 'CordovaPlugins'

node.js - Ionic - 未安装 Cordova CLI

css - ionic - 在 iOS 10 的输入字段中复制/粘贴不起作用

java - 在 Java 中使用 Javascript cookie

javascript - 仅从 ID 字段中检索数字

javascript - 在 Angularjs 中将字节数组转换为 Base64 字符串

javascript - 我可以阻止 babeljs 将函数转换为本地变量吗?