将对象数组保存到本地存储不工作

Saving Object Array to local storage not working

本文关键字:存储 工作 对象 数组 保存      更新时间:2023-09-26

你好,我试图创建一个简单的客户端购物车,在我的控制器中,当页面加载时,我定义了数组对象,将持有我的项目,如果它们是未定义的或有0的长度,我设置它们默认为'[]':

$scope.cart = JSON.parse($window.localStorage.getItem('cart')) || [];
$scope.cart.items = $scope.cart.items || [];

这是将商品添加到购物车中的函数:

$scope.addItem = function(item) {
    if (item.quantity > 0)
    {
        var cartItem = {
            id: item.id,
            description: item.class + ' item' + (item.quantity > 1 ? 's' : '') + ' to ' + $scope.details.name,
            quantity: item.quantity
        }
        // Adding item to cart array
        $scope.cart.items.push(cartItem)
        // Saving cart to storage
        $window.localStorage.setItem('cart', JSON.stringify($scope.cart));
        // Checking to see if data has indeed been stored in localstorage
        console.log(JSON.parse($window.localStorage.getItem('cart')));
    }
}

现在我的购物车在存储总是显示为空,有几次我玩了代码,让它工作(不知道我做了什么),但当我重新加载页面时,一切都被清除。

您将cart初始化为数组,但随后为其分配属性。

应该是一个对象:

$scope.cart = JSON.parse($window.localStorage.getItem('cart')) || {};

同样,在您可以将push转换为cart中的数组之前,需要定义该数组。

最简单的可能是首先在一个对象中提供所有属性:

var newCart = {
    tickets:[],
    items:[]    
}
$scope.cart = JSON.parse($window.localStorage.getItem('cart')) || newCart ;

您应该检查是否已经有一个值存储为

if(!$window.localStorage.getItem('cart'))
{
// Saving cart to storage
        $window.localStorage.setItem('cart', JSON.stringify($scope.cart));
}