首页 > 解决方案 > 错误语法错误: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>    

标签: node.jsangular

解决方案


首先,在您的 else 语句中,您没有调用该方法,只是将函数名作为值传递:

this.shopping_cart_items.push(product);

     localStorage.setItem('shopping_cart', JSON.stringify(this.get_shopping_cart_items())) <--- changed this to method call

而且,这就是为什么它在将字符串转换为 JSON 对象时给您一个错误的原因。


推荐阅读