moris62
moris62

Reputation: 1045

Angular can not read property of undefined

I have the following in my component:

public allStats:any;
getAllTurbinesStat(id:string) {

  this.service.getAllTurbinesStat(id).subscribe(s => {
   this.allStats=s;
  });
 }

in my html:

 <div class="card-body align-items-center d-flex justify-content-center">      
           {{ allStats[0].all }}
           </div>  

it actually works and shows the data but in my console, i get this error? why is that? and if it does not recognize why does it show the value on my browser?

the data i get from back end is:

0: {all: 2, starT_UP: 3, service: 5, run: 183, linK_DOWN: 75, …}

Upvotes: 0

Views: 472

Answers (2)

Reza
Reza

Reputation: 19843

the issue is when component is rendered value is undefined

 <div class="card-body align-items-center d-flex justify-content-center" *ngIf="allStats && allStats.length">      
           {{ allStats[0].all }}
           </div>  

Upvotes: 1

code-gorilla
code-gorilla

Reputation: 2408

Your api call will not be done before the first render, so allStats will stille be undefined.

There is a typical pattern used in SPAs, where there are multiple cases for async data in the template:

  • loading
  • loaded

This can e.g. look like this:

<ng-container *ngIf="allStats; else loading">
  {{ allStats[0].all }}
</ng-container>
<ng-template #loading> ...loading </ng-template>

Upvotes: 1

Related Questions