Home > OS >  For Loop Not Passing Id Angular
For Loop Not Passing Id Angular

Time:01-11

I want to pass the res[i].id to my ArrayList but it gives me this result anyone know how to fix it? ..............

0: {id: 0, ArrayListID: 809, VarName: "TEST001A"}
1: {id: 0, ArrayListID: 806, VarName: "TEST002A"}
2: {id: 0, ArrayListID: 0, VarName: "TEST001B"}         //result
3: {id: 0, ArrayListID: 0, VarName: "TEST002B"}


809
809    // here is the res[i].id 
806
806


varName:any[] = [];

postTesting(){
  this.serv.postTest(this.fg.value?.dRay).subscribe((res:any[])=>{
    console.log(res)
    for(var i = 0; i < this.res.length; i  ){
      res[i].id = this.varName[i].ArrayListID
    }

    this.serv.postTest1(this.varName).subscribe((r)=> {
      console.log()
    })
  })
}

CodePudding user response:

If I have understood the question correctly, I think you may have the assignment the wrong way around?

for(var i = 0; i < this.res.length; i  ){
  res[i].id = this.varName[i].ArrayListID
}

should be

for(var i = 0; i < this.res.length; i  ){
  this.varName[i].ArrayListID = res[i].id
}

This will then allow you to provide an updated this.varName to your serv.postTest1 call. Currently you are assigning data from this.varName to your temporary variable res so this.varName remains unchanged.

Note: As @churill recommended yesterday, it would be worth reading up on avoiding nested subscribes https://www.thinktecture.com/en/angular/rxjs-antipattern-1-nested-subs/

CodePudding user response:

you're using this.res.length for response, try using res.length

for(var i = 0; i < res.length; i  ){
   this.varName[i].ArrayListID = res[i].id
}
  • Related