Angular模板访问数组下标0报错Cannot read property '0' of undefined求助
问题原因
这个报错是异步请求和模板渲染的时序不匹配导致的:
- 你在TS中仅声明了
details变量,没有赋初始值,组件初始化阶段details的默认值为undefined - Angular模板会在组件初始化完成后立即触发首次渲染,而HTTP请求是异步操作,首次渲染时接口还没有返回数据,
details还没被赋值,此时模板执行details[0].name会尝试读取undefined的0属性,直接抛出类型错误。
解决方法
下面是3种常用的可行方案,按需选择即可:
方案1:使用Angular安全导航操作符(?.)
改动最小的方案,在模板读取可能为空的属性前加?.,Angular会自动判断前序值是否为null/undefined,为空就终止属性读取,不会抛出错误:
<div class="p-5 text-center bg-light bg" style="height: 300px;" > <h1 class="mb-3"><span style="color: white;">Welcome to</span> <span style="color:gold;"> {{details?.[0]?.name}}</span></h1> <h4 class="mb-3"></h4> <!-- 注意原代码title后多了多余的字符t,此处一并删除 --> <h2 style="color: white;">{{details?.[0]?.title}}</h2> </div>
方案2:用*ngIf控制渲染时机
给外层容器加判断逻辑,等details有有效值之后再渲染内部内容,还可以搭配加载提示优化用户体验:
<div *ngIf="details?.length; else loading" class="p-5 text-center bg-light bg" style="height: 300px;" > <h1 class="mb-3"><span style="color: white;">Welcome to</span> <span style="color:gold;"> {{details[0].name}}</span></h1> <h4 class="mb-3"></h4> <h2 style="color: white;">{{details[0].title}}</h2> </div> <ng-template #loading> <div class="p-5 text-center bg-light bg" style="height: 300px;">数据加载中...</div> </ng-template>
方案3:给变量设置初始默认值
在TS声明details时直接赋值为空数组,从根源避免读取undefined的属性:
export class HeaderComponent implements OnInit { // 初始赋值为空数组 public details: any[] = [] url="http://127.0.0.1:8000/aboutus/?format=json" constructor(private http: HttpClient, private route :Router){ this.http.get(this.url).toPromise().then(data=>{ console.log(data) this.details=data }); } ngOnInit() {} }
额外优化建议
不建议把HTTP请求逻辑写在constructor中,Angular的constructor仅用于依赖注入,业务请求逻辑建议放到ngOnInit生命周期钩子中,更符合框架规范。
内容的提问来源于stack exchange,提问作者Aniket Thorat
相关产品推荐
相关产品推荐

