Angular中ngOnInit嵌套for循环失效及页面加载异常求助
问题描述
我尝试通过嵌套for循环访问对象数组中每个对象内部的infos数组,并将其中的元素存入新数组newArr。目前遇到两个问题:
- 外层循环可正常执行,但内层循环似乎没有将元素存入newArr(控制台打印显示infos数组存在数据);
- 当把这段逻辑放在ngOnInit中调用时,页面持续加载无法正常显示,但我需要页面打开时就加载这些数据。
TS代码
newArr: any = []; list: any = [ { nome: 'testing', isso: 'example', infos: [ {nome: "ingrid", idade: 12, destino: "manaus", carbs: 333334}, {nome: "ester", idade: 22, destino: "coreia", carbs: 10988}, {nome: "sara", idade: 52, destino: "los angeles", carbs: 2234}, {nome: "laura", idade: 32, destino: "peru", carbs: 789}, {nome: "priscila", idade: 40, destino: "rio de janeiro", carbs: 654}, {nome: "paula", idade: 39, destino: "londres", carbs: 3456}, {nome: "simone", idade: 42, destino: "bahia", carbs: 987}, {nome: "leticia", idade: 26, destino: "argentina", carbs: 234}, {nome: "raissa", idade: 41, destino: "sao paulo", carbs: 1234}, {nome: "ana", idade: 15, destino: "suecia", carbs: 45677}, ] }, { nome: 'testing two', isso: 'example two', infos: [ {nome: "james", idade: 22, destino: "manaus", carbs: 333334}, {nome: "steve", idade: 32, destino: "coreia", carbs: 10988}, {nome: "paulo", idade: 51, destino: "los angeles", carbs: 2234}, {nome: "levi", idade: 32, destino: "peru", carbs: 789}, {nome: "matheus", idade: 43, destino: "rio de janeiro", carbs: 654}, {nome: "roberto", idade: 39, destino: "londres", carbs: 3456}, {nome: "simon", idade: 82, destino: "bahia", carbs: 987}, {nome: "lucas", idade: 56, destino: "argentina", carbs: 234}, {nome: "stefan", idade: 41, destino: "sao paulo", carbs: 1234}, {nome: "ian", idade: 12, destino: "suecia", carbs: 45677}, ] } ]; // 原循环逻辑(建议放入ngOnInit中) for (let i = 0; i < this.list.length; i++) { let cd = this.list[i]; console.log(cd); if(cd.infos){ for(let j = 0; j < cd.infos.length; j++){ const name = cd.infos[j]; this.newArr.push(name); } } }
HTML代码
<ng-container> <table> <tr> <th>Nome</th> <th>Destino</th> <th>Idade</th> <th>carbs</th> </tr> <tr *ngFor="let item of newArr"> <td>{{item.nome}}</td> <td>{{item.idade}}</td> <td>{{item.destino}}</td> <!-- 原代码此处缺少闭合的}} --> <td>{{item.carbs}}</td> </tr> </table> </ng-container>
解决方案
修复模板语法错误
HTML代码中<td>{{item.destino}</td>缺少闭合的双大括号}},这会导致Angular模板解析失败,直接引发页面无限加载。修正后应为:<td>{{item.destino}}</td>。规范逻辑执行时机
将数据处理的循环逻辑放入ngOnInit生命周期钩子中,确保组件初始化时仅执行一次:ngOnInit(): void { for (let i = 0; i < this.list.length; i++) { let cd = this.list[i]; if(cd.infos){ for(let j = 0; j < cd.infos.length; j++){ this.newArr.push(cd.infos[j]); } } } }简化数据处理逻辑(可选)
用Array.flatMap替代嵌套for循环,代码更简洁且可读性更高,同时避免手动循环可能出现的错误:ngOnInit(): void { this.newArr = this.list.flatMap(item => item.infos || []); }
内容的提问来源于stack exchange,提问作者starr
相关产品推荐
相关产品推荐

