Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4 copy object without reference?

Inside a component I tried to copy an object from a service that could be modified inside the component, but should stay in the service.

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';
}

after the init both, this.test.someProperty as well as this.someService.test.someProperty are changed to new even though the last should stay old?

Why is that happening, and how to only change properties of this.test

like image 837
Max Solid Avatar asked Sep 20 '17 18:09

Max Solid


People also ask

How do you avoid reference copy in TypeScript?

So everyone needs to copy an object into another variable but we don't need to reference it, we need to create a new object from the copying object. So, on JavaScript & TypeScript languages, we have the option to do that in multiple ways. But we have used the “newObject = {… Object}” thing commonly in typescript.

Can we create object without reference?

no. When you later "initialize" the variable, you are assigning a reference to the variable. You are not copying the fields of the object.


1 Answers

Actually Object assign works as in your example. Created plunker to prove it

  this.test = Object.assign({}, this.someService.test);
like image 85
alexKhymenko Avatar answered Oct 25 '22 19:10

alexKhymenko