簡體   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