你好,我正在尝试创建一个简单的客户端购物车,在我的 Controller 中,当页面加载时,我定义了将保存我的项目的数组对象,如果它们未定义或长度为 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 ;
关于javascript - 将对象数组保存到本地存储不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32669066/