R.Boguslawski R.Boguslawski - 9 months ago 74
JSON Question

Cannot read property 'name' of null Angular2 JSON

I got this code in AppComponent:

let pageToView = page*10 + 10;

for(var i=0; i<pageToView; i++){


ngOnInit() {
this.http.get('app/planets.json').subscribe(res => {
this.planets = res.json();

And I have this in template:

{{planetsToView[0].name | json}}

I have got problem:

When I tried with {{planetsToView[0] | json }} it works but contain another properties also.

Answer Source

Could be this problem:

At the time your component is initialized your JSON is not yet loaded into this.planets because the http.get call is asynchronous. Can you try this in your template: (Note the ? which is added)

{{planetsToView[0]?.name | json}}