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
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 = []; // code changed
...
getPosts() {
this.http.get('https://reqres.in/api/users?page=3').subscribe(res =>
this.results = res.data); // code changed
}
}
{{ result | json }}
2) Use safe navigation operator
{{ result | json }}
But it's standard practice to use the second way.