繁体   English   中英

Angular:ERROR TypeError:无法读取undefined的属性___

[英]Angular: ERROR TypeError: Cannot read property ___ of undefined

即使值在浏览器中呈现,我也会收到这些错误。 我不知道如何解决这个问题。

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

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

宾语:

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

因为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

<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响应没有所有预期的属性。

添加像我上面建议的检查应该可以解决您的问题。 LMK,如果我可以进一步解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM