如何保护阵列不被刷新

时间:2019-09-09 13:55:54

标签: javascript html arrays angular typescript

我有基于“衣服和订单”模型的衣服和订单表和数组。每当我将衣服元素推入“订单”数组,尤其是更新所选衣服的数量和价格时,衣服数组也将更新,我也没有不想。我想让数组保持不变。我在互联网上搜索了数组但没有用。这是我在下面尝试的方法。为了清楚起见,我将在此处添加图片

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);
   }
  }
}

3 个答案:

答案 0 :(得分:2)

这是因为衣服和订单数组中的元素共享相同的引用,因此您需要深度克隆对象以破坏引用: 请尝试以下操作:

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
        }
    }

答案 1 :(得分:1)

尝试

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

这会将对象的副本添加到订单列表中,而不是对其的引用

答案 2 :(得分:0)

正如其他人提到的那样,您传递给Clothes的{​​{1}}对象是对onAddItem中相应的Clothes对象的引用,因此当您对其进行突变时对象,它将改变原始对象。

如果clothesList是一个简单的类,则可以使用传播运算符进行复制:

Clothes

您还可以使用onAddItem(value) { let copyOfValue = {...value}; ... } 构造函数进行复制:

Clothes