Angular:错误 TypeError:无法读取未定义的属性 ___
2018-04-08
14518
即使值在浏览器中呈现,我也会收到这些错误。我不确定如何修复此问题。
ERROR TypeError: Cannot read property 'length' of undefined
ERROR TypeError: Cannot read property 'FirstName' of undefined
Component.ts:
teams: Team[];
ngOnInit() {
this.getTeams();
}
constructor(private m: DataManagerService, private router: Router) {
}
getTeams(): void {
this.m.getTeams().subscribe(teams => this.teams = teams);
}
select(em: Team){
this.router.navigate(['/teamView',em._id]);
}
Component.html:
<div class="panel-body">
<table class="table table-striped">
<tr>
<th>Team name</th>
<th>Name of Team Leader</th>
</tr>
<tr *ngFor='let team of teams' (click)="select(team)">
<td>{{team.TeamName}}</td>
<td>{{team.TeamLead.FirstName}} {{team.TeamLead.LastName}}</td>
</tr>
</table>
<hr>
</div>
Team.ts:
export class Team {
_id: string;
TeamName: string;
TeamLead: Employee;
Projects:{};
Employees: {};
}
对象:
DataManagerService.ts
teams: Team[];
projects: Project[];
employees: Employee[];
constructor(private http: HttpClient) {
}
getTeams(): Observable<Team[]> {
return this.http.get<Team[]>(`${this.url}/teams`)
}
getProjects(): Observable<Project[]> {
return this.http.get<Project[]>(`${this.url}/projects`)
}
getEmployees(): Observable<Employee[]> {
return this.http.get<Employee[]>(`${this.url}/employees`)
}
2个回答
因为
teams
可能尚不可用,
您可以尝试这种方式:
<div class="panel-body">
<table class="table table-striped">
<tr>
<th>Team name</th>
<th>Name of Team Leader</th>
</tr>
<tr *ngFor='let team of teams' (click)="select(team)">
<td>{{team.TeamName}}</td>
<td>{{team.TeamLead?.FirstName}} {{team.TeamLead?.LastName}}</td>
</tr>
</table>
<hr>
</div>
工作演示:
https://stackblitz.com/edit/angular-tutorial-2yzwuu?file=app%2Fapp.component.html
HDJEMAI
2018-04-08
<tr *ngIf='teams.length > 0' *ngFor='let team of teams' (click)="select(team)">
<td>{{team?.TeamName}}</td>
<td>{{team?.TeamLead?.FirstName}} {{team?.TeamLead?.LastName}}</td>
</tr>
可能性: a) Teams 对象尚未填充。因此没有内容可以迭代 b) 您的 API 响应不包含所有预期属性。
添加我上面建议的检查应该可以解决您的问题。如果我可以进一步解释,请告诉我。
Bimal Paul
2018-04-08