Angular 6 - Object Properties Updating without Setting them

ぃ、小莉子 提交于 2019-12-11 16:58:51

问题


I have an editor where the user can edit a product. I save an instance of the product in ngOnInit under initialProduct to make it possible to reset the edits.

Unfortunately, I have a weird issue: When adding a new tag the properties of the initialProduct changes without setting them.

Here is a stackblitz:

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


回答1:


With this code

this.initialProduct = this.product;

you are assigning to this.initialProduct the same variable positioned at the memory index related by this.product. This because this.product points to a memory address and with the previous operation you are copying only the memory address. So this.product and this.initialProduct point to the same variable.

You need to create another array and to copy this.product values into this.initialProduct (new array).

You can do this by various ways. For example:

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

or

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

or

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



回答2:


because of references

this.tags = this.product.tags;

You can do the following (ES6):

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


来源:https://stackoverflow.com/questions/52651051/angular-6-object-properties-updating-without-setting-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!