John C
John C

Reputation: 517

Angular: ERROR TypeError: Cannot read property ___ of undefined

I'm getting these errors even though the values renders in the browser. I'm not sure how to fix this.

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

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

Upvotes: 5

Views: 14638

Answers (2)

HDJEMAI
HDJEMAI

Reputation: 9820

Because teams is probably not yet available,

you can try this way:

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

Working demo:

https://stackblitz.com/edit/angular-tutorial-2yzwuu?file=app%2Fapp.component.html

Upvotes: 3

Bimal Paul
Bimal Paul

Reputation: 48

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

Possibilities : a) Teams object hasn't been populated yet. Hence there is nothing to iterate over b) Your API response doesn't have all the expected properties.

Adding checks like I suggested above should fix your problem. LMK if I can explain further.

Upvotes: 2

Related Questions