为什么控制台在从Angular API获取数据后会给出错误



我正在从API获取数据,并希望为每个对象值显示选项卡。一切正常,只是在控制台中出现错误。Cannot read properties of undefined (reading 'Projects')数据正常显示。我假设它一开始不能读取它,所以它说它是未定义的。获取数据后显示

我该如何消除这个错误?

HTML:

<mat-tab *ngFor="let object of projects.Projects; let i = index" label="{{ object.Id }}"></mat-tab>

组件:

import { Component, OnInit } from '@angular/core';
import { TablesService } from "../tables/tables.service";
@Component({...})
export class MyComponent implements OnInit {
projects: any;
constructor(public tableService: TablesService)
{
this.tableService.fetchAPI().subscribe((data) => {
this.projects = data;
})
}
ngOnInit(): void {
}
}

这是发生的,因为projects只是声明而不是初始化,所以直到你的API调用完成,你把一些数据在该变量,它将是undefined。处理这个问题的一种方法是假设projects可能是undefined,并使用?(可选的链接操作符)来解释:

<mat-tab *ngFor="let object of projects?.Projects; let i = index" label="{{ object.Id }}"></mat-tab>

另一个解决方案是给projects属性一个初始值:

projects: any = {};

模板将在服务器响应之前呈现

这里projects暂时是undefined

<mat-tab *ngFor="let object of projects.Projects; let i = index" label="{{ object.Id }}"></mat-tab>

你可以使用*ngIf来防止这个部分被渲染,直到projects被定义。但是,由于只能放置一个结构操作符,因此必须在其周围添加ng-container:

<ng-container *ngIf="projects">
<mat-tab *ngFor="let object of projects.Projects; let i = index" label="{{ object.Id }}"></mat-tab>
</ng-container>

或者你也可以在projects之后添加?,像这样:

<mat-tab *ngFor="let object of projects?.Projects; let i = index" label="{{ object.Id }}"></mat-tab>