Angular 8获取数组length时报错:TypeError: Cannot read property 'length' of undefined
解决Angular中"Cannot read property 'length' of undefined"的问题
嘿,我来帮你搞定这个报错!咱们先把问题根源理清楚:
你在组件类初始化时直接把count赋值为this.organismesFinanceurs.length,但这里有两个关键问题:
organismesFinanceurs只声明了类型,没有初始化,默认是undefined,直接访问它的length属性肯定会触发报错;- 数组数据是通过HTTP请求异步获取的,
ngOnInit里的订阅回调要等请求完成后才会执行,在这之前organismesFinanceurs根本还没拿到后端返回的数据。
下面给你两种实用的解决方案:
方案一:初始化空数组+异步数据返回后同步变量
先把数组初始化为空数组,这样一开始length就是0,不会触发undefined报错,等数据返回后再更新count和分页配置:
count: number = 0; // 初始化空数组,避免undefined状态 organismesFinanceurs: OrganismeFinanceur[] = []; config: any = { itemsPerPage: 7, currentPage: 1, totalItems: this.count }; ngOnInit() { this.serviceHttp2.getAllOrganismes().subscribe(resp => { // 给数组赋值后端返回的数据 this.organismesFinanceurs = resp; // 同步更新count和分页配置的总条目数 this.count = resp.length; this.config.totalItems = this.count; }); }
方案二:直接在异步回调中处理分页配置
如果count变量不是业务必须的,也可以简化代码,直接在数据返回后更新分页配置的totalItems:
// 初始化空数组 organismesFinanceurs: OrganismeFinanceur[] = []; // 先将总条目数设为0 config: any = { itemsPerPage: 7, currentPage: 1, totalItems: 0 }; ngOnInit() { this.serviceHttp2.getAllOrganismes().subscribe(resp => { this.organismesFinanceurs = resp; // 数据返回后直接更新分页总条目数 this.config.totalItems = resp.length; }); }
核心思路总结:异步数据的处理必须等请求完成后再执行,组件初始化阶段不要依赖还未返回的异步数据,提前把数组初始化为空数组是避免undefined相关报错的常用小技巧。
内容的提问来源于stack exchange,提问作者Pelodido
相关产品推荐
相关产品推荐

