For循环不传递Id



我想传递res[I]。id到我的数组列表,我希望结果将是有序的。有人知道809和806是怎么回事吗。在数组列表

中没有修补
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 < res.length; i++){
this.varName[i].ArrayListID = res[i].id
}
this.serv.postTest1(this.varName).subscribe((r)=> {
console.log()
})
})
}

如果我没理解错的话,我想你可能把作业弄反了?

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

应该

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

这将允许您为serv.postTest1调用提供更新的this.varName。当前您正在从分配数据this.varName您的临时变量res,使this.varName保持不变

注意:正如@churill昨天推荐的,关于避免嵌套订阅https://www.thinktecture.com/en/angular/rxjs-antipattern-1-nested-subs/

值得一读

你正在使用this.res.length作为响应,尝试使用res.length

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

我有点不清楚你的代码到底在做什么…特别是postTest方法返回的内容

但是像这样的事情可能会起作用:

this.generateIds()
.pipe(
map((ids) => {
var index = -1;
return ids.map((id) => { 
index += 1;
return { ...testData[index], ArrayListId: id }});
})
)
.subscribe((result) => console.log('result', JSON.stringify(result)));
}

generateIds()应该是这样的:this.serv.postTest(this.fg.value?.dRay)…假设这是该方法返回的内容

代码然后使用pipe处理发出的id数组。假设id作为数组返回。

map然后将id数组转换为使用这些id作为ArrayListId的数据数组。

在map内部,ids.map处理id数组中的每个条目。对于每个对象,它都将其映射到一个新对象,该对象具有原始对象属性和新的ArrayListId属性及其值。

结果是:

[{"id":0,"VarName":"TEST001A","ArrayListId":809},
{"id":0,"VarName":"TEST002A","ArrayListId":809},
{"id":0,"VarName":"TEST001B","ArrayListId":806},
{"id":0,"VarName":"TEST002B","ArrayListId":806}]

这接近你想要做的吗?

另外,正如其他人所说,最好避免嵌套订阅。更多信息,请看这个视频:https://youtu.be/KiJ-e5QuWe4

最新更新