I am learning how to use angular\'s new http client module. I get the error Cannot read property \'data\' of undefined when I try to consume the rest api. Here\'s my app.htm
Cannot read property 'data' of undefined simply means that results in not defined. Put console.log or apply breakpoints and try to find out why its not getting defined. When we apply breakpoints we can find out the exact reasons why it is not getting defined. Knowing the reason is important.
Since you are making a asynchronous request, initially results will be undefined, use a safe navigation operator
to check if the results exists and then access the data
<div *ngFor="let result of results?.data">
{{ result | json }}
</div>
Issue is same as explained by @Sajeetharan :
Since you are making a asynchronous request, initially results will be undefined,
You can solve it by 2 ways :
1) Provide some initial value from the very beginning:
export class AppComponent implements OnInit {
results:Array<any> = []; // code changed
...
getPosts() {
this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res =>
this.results = res.data); // code changed
}
}
<div *ngFor="let result of results">
{{ result | json }}
</div>
2) Use safe navigation operator
<div *ngFor="let result of results?.data">
{{ result | json }}
</div>
But it's standard practice to use the second way.