Angular: 错误类型:TypeError,无法读取未定义的属性___。

5

尽管值在浏览器中呈现,我仍然遇到这些错误。 我不确定如何解决这个问题。

错误类型:TypeError:无法读取未定义的属性“长度”

错误类型:TypeError:无法读取未定义的属性“FirstName”

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: {};
}

Object:

https://lit-coast-73093.herokuapp.com/teams

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`)
}

1
.length只是获取对象的大小。如果我删除<td>{{team.TeamLead.FirstName}} {{team.TeamLead.LastName}}</td>,它就可以工作了。 - John C
@John C: 你能否编辑并在你的问题中添加“select(team)”的代码? - HDJEMAI
@HDJEMAI 在 component.ts 中选择(team)。 - John C
“Project”类的内容是什么? - HDJEMAI
2个回答

3

由于 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


您不需要在“team”后面加上“?”,因为“team”永远不会为空。如果它为空,“*ngFor”将永远不会被执行。 - Zze

2
<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)团队对象尚未填充。因此,没有可迭代的内容。 b)您的API响应缺少所有预期的属性。
像我上面建议的添加检查应该可以解决您的问题。如果需要进一步解释,请告诉我。

实际上,我认为你应该将这里的*ngIf更改为:*ngIf ='teams!= null && teams.length> 0',否则如果getTeams()返回null,则会显示错误Cannot read property 'length' of null - Zze
1
这甚至无法编译。错误:模板解析错误:一个元素上不能有多个模板绑定。只使用一个名为“template”或带有*前缀的属性。 - Zze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接