I'm building a little d&d app to practice passing data components in angular and I'm hitting a strange issue.
I'm getting a "monster" object back from an API call and then populating that to the view a certain number of times. I'm trying to change one of the values, "name" by adding an index - simple - get "name" add and index. I'm getting the value for "name" changing it, and then pushing it to an array held in the component - all works fine. I'm thinking that the original value should be unchanged for the next iteration of the loop but this is not the case. Something i'm not understanding in scope here.
trying to only post a bit of the code as I know where the issue is and I know its a scope issue I just want to know why this is happening as a concept as Its something I'm not familiar with. Using
export class CombatComponent implements OnInit {
selected:number;
monsters:any[] = []
addedMonsters:any[] =[]
monsterNumber:number = 0; <----this is being passed from a form - its working
constructor( private ms:MonsterService) { }
<-dont want to post the entire function because this is where the issue lies ->
this.$monsterData.subscribe(data =>{
this.currentMonster=data;
for (let i = 0 ; i<this.monsterNumber; i++){
let originalName = this.currentMonster.name;
console.log(this.currentMonster.name)
this.monsters.push(this.currentMonster)
let newName = this.monsters[i]['name'] = this.currentMonster.name +" " + `${i+1}`
this.monsters[i].name = newName
console.log(this.monsters)
}
My issue is that after the first Iteration, what I think should happen is an array with a name + an index. Whats really happening is that the second time through the "name" value for currentMonster gets changed to the original value + index. What is it about scope im not understanding here?