克隆对象TypeScript [英] Cloning objects TypeScript
问题描述
我正在使用TypeScript使用Angular 2.我有用户管理组件,其中有完整的用户表.
I am working with Angular 2 with TypeScript. I have User Management component where I have table of whole users.
当单击表中的任何用户时,窗体将显示其全部属性进行编辑.选择用户发生事件如下:
When any user in table is clicked then forms appeaer with his whole properties to edit. Choosing user occurs event as below:
onUserSelected(event) {
var selectedId = event.data.id;
this.selectedUser = this.users.filter(user => user.id === selectedId)[0]
}
问题在于,当编辑selectedUser时,他的属性也会在表中更改,而且看起来不太好.我尝试如下创建自己的副本,但无济于事-用户类
The problem is when selectedUser is being edited his properties also changes in table and it doesnt look so good. I tried to create copy myself as below but it didn't help - user class
clone() {
var cloned = new User(this.id, this.login, this.name, this.surname, this.phone);
return cloned;
}
也许我做的事情不是Angular2的好习惯?
Maybe I am doing something which is not good practice in Angular2?
推荐答案
尝试使用
this.user = Object.assign({}, currentObject);
如@AngularFrance所述,这仅适用于浅拷贝对象,如果需要深拷贝对象,则寻求另一种实现.
As mentioned by @AngularFrance, this will only work for shallow-copying objects, seek another implementation if there's a need to deep-copy an object.
这篇关于克隆对象TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!