0

I have a service in angular, where I stored an array called array_item obtained from my api call and in the component I declared 2 variables called var_1 and var_2 where both have the same value which I've obtained from the service

i.e: var_1 = this.service.array_item && var_2 = this.service.array_item

I'm listing it in my HTML as lists of 2 DIVs but when I update the value in the list_1 it changes the array item value in service which automatically changes my array item data in list_2. I don't want list 2 to get changed I want it to be constant. Suggestions or solutions are welcome.

Thanks in advance

VinoPravin
  • 947
  • 3
  • 17
  • 32

2 Answers2

3

Yes this behavior is obvious because JavaScript is pass by reference. So you can solve the problem by keeping 2 other copies of the original array in component level.

Copying can be done as explained in this Reference

Then component code will be like,

var_1 = this.service.array_item.copy() // Implement copy function
var_2 = this.service.array_item.copy() // Implement copy function
Rahal Kanishka
  • 720
  • 13
  • 27
Malindu Sandaruwan
  • 1,477
  • 2
  • 13
  • 27
  • 1
    Hello as I've mentioned in the answer you have to implement the copy functionality. You can refer the Reference link in my answer to do that – Malindu Sandaruwan Jul 18 '18 at 08:58
1

This is happening due to you assign same value to both variable or you can call it shallow copy. All you need to do clone value using deep clone. Simplest way to do this is:

var_1 = this.service.array_item
var_2 = JSON.parse(JSON.stringify(this.service.array_item))

OR

var_2 = [...this.service.array_item]

OR

var_2 = this.service.array_item.slice()

For more reference about deep copy vs shallow copy you can check this link

jack
  • 589
  • 8
  • 22
  • This JSON approach is performance intensive. So you can look in to the this also https://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript – Malindu Sandaruwan Jul 17 '18 at 07:40
  • 1
    yes it slow but it is one of the way, otherwise we can use spread operator – jack Jul 17 '18 at 07:45
  • This json parse and json stringify works fine for me, but not the slice and spread method. Is there any reason for that? – VinoPravin Jul 18 '18 at 08:52