【问题标题】:Angular 6 - Object Properties Updating without Setting themAngular 6 - 对象属性更新而不设置它们
【发布时间】:2019-03-10 02:26:08
【问题描述】:

我有一个编辑器,用户可以在其中编辑产品。我在initialProduct 下的ngOnInit 中保存了一个产品实例,以便重置编辑。

不幸的是,我遇到了一个奇怪的问题:添加新标签时,initialProduct 的属性会在未设置的情况下更改。

这是一个堆栈闪电战:

https://stackblitz.com/edit/angular-yxrh2d?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

    标签: html angular typescript angular6


    【解决方案1】:

    因为引用

    this.tags = this.product.tags;
    

    您可以执行以下操作(ES6):

    this.tags = [...this.product.tags];
    

    【讨论】:

      【解决方案2】:

      使用此代码

      this.initialProduct = this.product;
      

      您将分配给this.initialProduct 的相同变量位于与this.product 相关的内存索引处。这是因为this.product 指向一个内存地址,而在前面的操作中,您只复制了内存地址。所以this.productthis.initialProduct 指向同一个变量。

      您需要创建另一个数组并将this.product 值复制到this.initialProduct(新数组)。

      您可以通过多种方式做到这一点。例如:

          // this.initialProduct = this.product;
          this.initialProduct = {
            tags: Array.from(this.product.tags)
          }
      

          // this.initialProduct = this.product;
          this.initialProduct = {
            tags: this.product.tags.concat()
          }
      

          // this.initialProduct = this.product;
          this.initialProduct = {
            tags: this.product.tags.slice()
          }
      

      【讨论】:

      • 我不知道这个 :D 非常感谢!
      猜你喜欢
      • 2016-08-12
      • 2018-10-25
      • 2017-05-22
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多