node.js - 错误语法错误:JSON.parse 中位置 0 处的 JSON 中的意外标记 u()
问题描述
我想在添加商品时更新我的购物车,但我一直在浏览器上收到此错误,我认为这是我的购物车没有更新的原因。
购物车.services.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
shopping_cart_items:any[]=[];
constructor() { }
addProduct = (product) =>{ //
let items = this.get_shopping_cart_items();
if(items){
items.push(product);
localStorage.setItem('shopping_cart', JSON.stringify(items));
}else
{
this.shopping_cart_items.push(product);
localStorage.setItem('shopping_cart', JSON.stringify(this.get_shopping_cart_items));
}
}
get_shopping_cart_items =()=>{
let items = localStorage.getItem('shopping_cart');
return JSON.parse(items);
}
getCartLength =()=>{
let items = this.get_shopping_cart_items();
return items? this.get_shopping_cart_items().length:0
}
}
文件:
<div class = "header_menu_cart">
<mat-icon>shopping_cart</mat-icon>
<p class = "header_cart_number">{{shoppingCart.getCartLength()}}</p>
解决方案
首先,在您的 else 语句中,您没有调用该方法,只是将函数名作为值传递:
this.shopping_cart_items.push(product);
localStorage.setItem('shopping_cart', JSON.stringify(this.get_shopping_cart_items())) <--- changed this to method call
而且,这就是为什么它在将字符串转换为 JSON 对象时给您一个错误的原因。
推荐阅读
- ios - backtrace 错过了导致崩溃的函数
- python - 每次在 Python 中按下相同的按钮时,如何按顺序更改海龟图像?
- windows - Jekyll 服务转换错误“没有这样的文件或目录”
- ubuntu - Linux SETFACL 不离开 /home
- python - 如何从 Odoo v11 中的按钮添加打印自定义报告?
- excel - Excel VBA:For循环 - 写入行号的值
- mysql - 速度和性能优化问题:多数据库模型 vs 单数据库
- python - (分布式)为什么所有 gpus 都给出相同的输出?
- maven - 是否可以在不下载 jar 文件的情况下使用 selenium webdriver?
- c# - 如何在存储的 json 对象数组字符串中搜索多个 id?