Angular 6-更新对象属性而不设置它们 [英] Angular 6 - Object Properties Updating without Setting them
问题描述
我有一个编辑器,用户可以在其中编辑产品.我将产品实例保存在initialProduct
下的ngOnInit
中,以便可以重置编辑.
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.
不幸的是,我遇到一个奇怪的问题:添加新标签时,initialProduct
的属性会更改而未设置.
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
推荐答案
使用此代码
this.initialProduct = this.product;
您正在为this.initialProduct
分配与this.product
相关的位于内存索引处的相同变量.这是因为this.product
指向一个内存地址,并且通过先前的操作,您仅复制了该内存地址.因此this.product
和this.initialProduct
指向同一个变量.
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.
您需要创建另一个数组,并将this.product
值复制到this.initialProduct
(新数组)中.
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)
}
或
// this.initialProduct = this.product;
this.initialProduct = {
tags: this.product.tags.concat()
}
或
// this.initialProduct = this.product;
this.initialProduct = {
tags: this.product.tags.slice()
}
这篇关于Angular 6-更新对象属性而不设置它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!