简体   繁体   中英

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

ie: 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM