异步改写函数后Angular模板出现lst_itm未定义错误求助
问题说明
为避免弹窗受服务器响应时间影响,我将数据请求函数改成了异步函数,相关代码如下:
异步请求函数代码
async GetAllItems(Items) { try { const response = await this.http.get<Items[]>(this.baseUrl + 'Items/Getall=' + items + '&SystemId=' + items).toPromise(); return response; } catch (err) { console.log(err); } }
HTML模板代码
<div *ngIf="All.lst_itm"> <div *ngFor="let items of All.lst_itm"> <mat-accordion> <mat-expansion-panel style=" width: 500px; background: black"> <cdk-virtual-scroll-viewport style="float: right;" itemSize="35" class="description"> <div *ngIf="A">{{items.ShowA}}</div> <div *ngIf="B">{{items.ShowB}}</div> </cdk-virtual-scroll-viewport> <br> </mat-expansion-panel> </mat-accordion> </div> </div>
报错信息
InformationComponent.html:18 ERROR TypeError: Cannot read properties of undefined (reading 'lst_itm')
我已经用*ngIf="All.lst_itm"做了空值判断,但还是出现这个错误,请问原因是什么?该怎么解决?需要补充其他信息吗?
原因分析
报错核心是All本身为undefined,而非All.lst_itm为undefined。当前的*ngIf="All.lst_itm"会先尝试读取All的lst_itm属性,但如果All还未初始化(比如异步请求未返回、All未被赋值),就会触发“读取undefined的属性”错误。
解决方法
方法一:补充
All的存在判断
修改*ngIf逻辑,先判断All是否存在,再验证lst_itm:<div *ngIf="All && All.lst_itm"> <!-- 原模板内容不变 --> </div>也可以使用Angular支持的可选链操作符简化:
<div *ngIf="All?.lst_itm"> <!-- 原模板内容不变 --> </div>方法二:提前初始化
All对象
在组件类中提前给All赋初始空值,避免它处于undefined状态:// 组件类中定义All时初始化 All: { lst_itm?: any[] } = {};额外修复:异步函数的参数错误
你的GetAllItems函数参数是大写Items,但内部使用的是小写items,会导致参数未正确传递、请求URL出错,建议修正:async GetAllItems(items: any) { try { const response = await this.http.get<Items[]>(`${this.baseUrl}Items/Getall=${items}&SystemId=${items}`).toPromise(); // 注意:请求返回后必须给组件的All赋值,比如 this.All = response; return response; } catch (err) { console.error(err); } }同时要确保调用
GetAllItems后,将返回值赋值给组件的All属性,否则All永远不会有数据。
内容的提问来源于stack exchange,提问作者Windows11
相关产品推荐
相关产品推荐

