【发布时间】:2023-01-11 12:32:44
【问题描述】:
我用*ngIf判断html中的数组长度
<div *ngIf="apps.length === 0">
并在 .ts 文件中定义应用程序
public apps: any[];
并且应用程序是从其余的 api 数据中检索到的:
ngOnInit() {
const refSpinner = this._simsSpinnerService.showSpinner('my-apps-spinner');
const getMyApps = this._myAppsService.getMyApps().pipe(share(), finalize(() => { this._simsSpinnerService.stopSpinner(refSpinner); }))
this._subscriptions.push(getMyApps.subscribe({
next: (data) => {
if (data && data instanceof Array) {
debugger
this.apps = data;
}
},
error: (err) => MessageService.addError(err)
}));
}
控制台将打印错误信息:
ERROR TypeError: Cannot read properties of undefined (reading 'length')
at MyAppsComponent_Template (my-apps.component.html:13:30)
我添加了调试器,发现 this.apps 在数据分配给它之前是未定义的。
然后我改变了初始化数据类型的方式,如:
public apps = [];
并且报错消失了,发现this.apps在数据赋值之前是一个数组。
我搜索并发现
any[] 是一个数组,其中项的类型为 any。
但为什么它是未定义的?它不应该是其中任何元素的数组吗?
【问题讨论】:
标签: arrays typescript initialization