簡體   English   中英

如何保護陣列不被刷新

[英]How to protect an array from being refreshed

我有衣服和訂單表和陣列,基於衣服和訂單模型。每當我將衣服元素推入訂單數組,尤其是更新衣服和價格選擇,衣服陣列也更新,我不想要它。我想保持我的數組不變。我在互聯網上搜索它但沒有工作。這就是我在下面嘗試的。也要說清楚我會在這里添加圖片

https://imge.to/i/vg2aYm

https://imge.to/i/vg2uvF

HTML

    <table class="table table-sm">
        <thead>
          <tr>
            <th scope="col">Clothes</th>
            <th scope="col">Price</th>
            <th scope="col"></th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let i of clothesList;let a = index">
            <td>{{i.name}}</td>
            <td>{{i.price}}$</td>
            <td><button class="btn btn-alert" (click)="onAddItem(i)" >Add To Cart</button></td>
          </tr>
        </tbody>
      </table>

   <table class="table" *ngIf="orders.length>0">
                    <thead>
                      <tr>
                        <th scope="col">Clothes</th>
                        <th scope="col">Amount</th>
                        <th scope="col">Price</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr *ngFor="let order of orders;">
                        <td>{{order.name}}</td>
                        <td>{{order.amount}}</td>
                        <td>{{order.price}}</td>
                      </tr>
                    </tbody>
                    <hr>
                    <strong>Total Cost: {{totalCost}}</strong>
                  </table>

TS

export class AppComponent  {
 private clothesList:Clothes[]=[
   new Clothes(1,'Hat',500,1),
   new Clothes(2,'Shoes',150,1),
   new Clothes(3,'Pants',100,1),
   new Clothes(4,'Jacket',200,1),
   new Clothes(5,'T-Shirt',120,1),
   new Clothes(6,'Souvether',150,1),
   new Clothes(7,'Scarf',400,1)
 ];
    private orders:Order[]=[];

    onAddItem(value)
  {   
   if(this.orders.find(i => i.name===value.name))
   {
      let myIndex= this.orders.indexOf(value);
      value.amount++;
      this.orders[myIndex].price+=this.orders[myIndex].price;
   } 
  else
   {
    this.orders.push(value);
   }
  }
}

這是因為衣服和訂單數組中的元素共享相同的引用,您需要深度克隆您的對象以打破引用:嘗試以下操作:

onAddItem(value){
        let order = this.orders.find(i => i.name === value.name);
        if (order) {
            value.amount++;
            order.price *= 2;
        }
        else {
            this.orders.push(JSON.parse(JSON.stringify(value))); // break the reference
        }
    }

嘗試

this.orders.push(angular.copy(value));

這會將對象的副本添加到訂單列表而不是它的引用

正如其他人所提到的,你傳遞給onAddItemClothes對象是對onAddItem中相應Clothes對象的clothesList ,所以當你改變那個對象時,它會改變原始對象。

如果Clothes是一個簡單的類,你可以使用spread運算符來制作副本:

onAddItem(value) {
   let copyOfValue = {...value};
   ...
}

您還可以使用Clothes構造函數進行復制:

onAddItem(value) {
   let copyOfValue = new Clothes(value.someProperty, value.anotherProperty, value.aThirdProperty, value.aFourthProperty);
   ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM