Max*_*lid 2 copy reference object angular
在组件内部,我尝试从可以在组件内部修改的服务中复制对象,但应该保留在服务中.
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';
}
Run Code Online (Sandbox Code Playgroud)
在init之后,this.test.someProperty以及this.someService.test.someProperty更改为new即使最后应该留下old?
为什么会这样,以及如何只改变属性 this.test
ale*_*nko 11
实际上对象分配的工作原理与您的示例一样。创建了 plunker来证明这一点
this.test = Object.assign({}, this.someService.test);
Run Code Online (Sandbox Code Playgroud)
Eek*_*s33 10
这是因为Object.assign是一个浅层合并,它只是合并顶层,所以顶层引用服务和组件中的同一个对象.
当我需要深度合并对象时,我个人使用lodash的合并:
this.test = _.merge({}, this.someService.test)
Run Code Online (Sandbox Code Playgroud)
另请参阅:如何深度合并而不是浅合并?
您还可以使用以下方法深度克隆对象:
this.test = JSON.parse(JSON.stringify(this.someService.test));
Run Code Online (Sandbox Code Playgroud)
另请参阅:如何在javascript中深度克隆