在组件内部,我试图从可以在组件内部修改的服务中复制一个对象,但应该留在服务中。
private test;
public ngOnInit(): {
console.log(this.someService.test.someProperty) //'old'
this.test = this.someService.test;
//not working as well?!
//this.test = Object.assign({}, this.someService.test);
//this.test = Object.create(this.somerService.test);
this.changeTest();
}
public changeTest(): void {
this.test.someProperty = 'new';
}
在初始化之后,
this.test.someProperty
以及 this.someService.test.someProperty
改为 new
即使最后应该留下 old
?为什么会发生这种情况,以及如何仅更改
this.test
的属性
最佳答案
这是因为 Object.assign 是浅层合并,它只是合并顶层,所以顶层在服务和组件中都引用了同一个对象。
当我需要深度合并对象时,我个人使用 lodash 的合并:
this.test = _.merge({}, this.someService.test)
另见:How to deep merge instead of shallow merge?
您还可以使用以下方法深度克隆对象:
this.test = JSON.parse(JSON.stringify(this.someService.test));
另见:How to Deep clone in javascript
关于Angular4 复制对象没有引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46329213/