0

Hope someone can help me understand this behavior in Angular.

There is a simple input bound to a component variable using ngmodel two way-data binding. When the component initializes, the data is retrieved using the dataService which returns an employee object which works fine. But the thing is when i edit the value in the input box, the component variable employee's name changes but also the data in the service as well is changed which according to me is very weird. The data returned from the service should not be affected right? Find plunker below.

Kindly refer to this plunker https://plnkr.co/edit/wjuJLo?p=preview

getData() {
    console.log(this.employee);
    console.log(this.service.getEmp());
  }

Thanks and Regards, Ashley

shammelburg
  • 6,974
  • 7
  • 26
  • 34
ashley
  • 1,008
  • 17
  • 37

2 Answers2

2

The problem is with this part of code.

ngOnInit() {
        this.employee = this.service.getEmp();
      }

In JavaScript, variables only hold a reference to the object, not the object itself. Thus this.employee have a reference to this.service.getEmp();

So whenever you change this.employee, it will change the value at the reference, thus the value you will get from the service will be the updated one, not the one you expected.

Inorder to clone,

Using jquery check this answer for more info:

// Shallow copy
this.employee = jQuery.extend({}, this.service.getEmp());

// Deep copy
this.employee = jQuery.extend(true, {}, this.service.getEmp());

Or using Object.assign:

this.employee = Object.assign({}, this.service.getEmp());

Or using Lodash:

this.employee = _.clone(this.service.getEmp()); 
Community
  • 1
  • 1
monica
  • 1,454
  • 14
  • 28
1

You are assigning getEmp() to this.employee means you assign getEmp() reference to this.empoyee so if you change anything to this.employee then that will get reflected to getEmp() too.

Here you will have to make sure that you will make a copy of getEmp() before assign it back to this.employee. And that will solve your issue.

Solution code is attached below

export class App implements OnInit {
  private employee: Employee = new Employee();
  constructor(private service: dataService) {

  }

  ngOnInit() {
    this.employee = Object.assign({}, this.service.getEmp());  // making copy of getEmp()
  }

  getData() {
    console.log(this.employee);
    console.log(this.service.getEmp());
  }
}

Cheers!

Suneet Bansal
  • 2,664
  • 1
  • 14
  • 18