【问题标题】:Add JSON item into localStorage将 JSON 项添加到 localStorage
【发布时间】:2020-03-21 23:48:39
【问题描述】:

我正在处理一个角度任务,目标是在添加到购物车之前将要购买的项目添加到 localStorage。

我有四个用户可以添加的不同对象,项目可以添加多次,所以一般情况是如果对象存在于 localStorage 并且用户在其他时间添加它我应该更新数量属性,如果不添加具有新属性的新对象数量 = 1。

这里是服务:

  addGiftToCard(type) {
    let cardParse = JSON.parse(localStorage.getItem('cart')) || []
    let index = _.findIndex(cardParse, item => item.type && item.id == type.id)
    if (index == -1) {
      type.qte = 1
      cardParse.push(type)
    } else {
      cardParse[index].qte += 1
    }
    localStorage.setItem('cart', JSON.stringify(cardParse))

  } 

以及我的组件中的功能:

 addGiftToCart(type) {
    let index = this.cartService.addGiftToCard({ type: type })
  }

html:

<div class="available-checks" *ngIf="!(types === null)">
    <div class="row checks-list">
      <div class="col-md-3" *ngFor="let type of types">
        <div class="card">
          <div class="card-body">
            <div class="row">
              <div class="col-8 logo-container justify-content-center">
                <img class="card-logo" src="../../../assets/images/logo-gold.svg" alt="">
              </div>
              <div class="col-4 icon-container justify-content-center text-center">
                <img [src]=" serverUrl+'/'+type?.image" alt="" style="width: 50px;height: 50px;">
              </div>
            </div>
            <div class="row desc-title-c">
              <p class="desc-title">Chèque cadeau</p>
            </div>
            <div class="row type-c">
              <p class="check-type">{{type.type}}</p>
            </div>
            <div class="offer-container">
              <p class="offer">{{type.designation}}</p>
              <p class="price">{{type.amount}}€</p>
            </div>
            <div class="">
              <button class="btn btn-footer" (click)="addGiftToCart(type)">Ajouter au panier</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

我在这里遇到的问题是一个对象添加了该项目是什么,只有数量属性计数器更新并获得了这样的 json 格式:

如果我在服务函数中设置 type = type.type 它可以工作并且我得到了这样的 json

我需要json元素类型不包含属性qty,qty应该像第一张图片一样在对象属性之外!

【问题讨论】:

标签: javascript arrays json angular local-storage


【解决方案1】:

我认为您应该使用item.type.id 而不是item.id,如下所示

 let index = _.findIndex(cardParse, item => item.type && item.type.id == type.id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    相关资源
    最近更新 更多