-2

I assigned a source variable to two different independent variables, but the second variable changes if I change the first one.

  list: Array<any> = [];
  savedList: Array<any> = [];

 constructor() { }

 ngOnInit() {
   this.sharedService.list.subscribe(response => {
   console.log('Component--List---', response);
   if (response) {
    this.list= response
    this.savedList= response
   }
  });
 }

onEvent(event){
  console.log('this.list---1---',this.list,'this.savedList',this.savedList);
  this.list.push(event.item.source);
  console.log('this.list---2---',this.list,'this.savedList',this.savedList);

}

Printed the console log for clarity:

Component--List--- (1)[{…}]
this.list---before---(1) [{…}] this.savedList (1)[{…}]
this.list---after--- (2) [{…}, {…}] this.savedList (2) [{…}, {…}]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
MPPNBD
  • 1,566
  • 4
  • 20
  • 36
  • `this.list = response` and `this.savedList = response` **do not** create copies of the list. They're just two references to exactly the same object. This is nothing to do with Angular, it's a basic fact of working with mutable objects in (among other languages) JavaScript. – jonrsharpe Jul 09 '18 at 21:56
  • it's interesting you expect different behavior – Kyle Burkett Jul 09 '18 at 22:11
  • Expecting some ways to achieve that – MPPNBD Jul 09 '18 at 22:23
  • Possible duplicate of [Javascript fastest way to duplicate an Array - slice vs for loop](https://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop) – georgeawg Jul 10 '18 at 01:30

2 Answers2

4

This is because your two variables are a reference to the original response object. Try:

if (response) {
    this.list= Object.assign({}, response);
    this.savedList= Object.assign({}, response);
   }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
jcroll
  • 6,875
  • 9
  • 52
  • 66
0

This worked what I was expected

if (response) {
    this.list= response;
    this.savedList= response.slice();
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
MPPNBD
  • 1,566
  • 4
  • 20
  • 36