VinoPravin
VinoPravin

Reputation: 987

Constant Service variable Angular

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

Upvotes: 0

Views: 579

Answers (2)

Malindu Sandaruwan
Malindu Sandaruwan

Reputation: 1517

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

Upvotes: 3

jack
jack

Reputation: 609

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

Upvotes: 1

Related Questions