R.Boguslawski R.Boguslawski - 5 days ago 5
JSON Question

Cannot read property 'name' of null Angular2 JSON

I got this code in AppComponent:

getPlanetsToView(page){
let pageToView = page*10 + 10;

for(var i=0; i<pageToView; i++){
this.planetsToView.push(this.planets.planets[i]);
}

}

ngOnInit() {
this.http.get('app/planets.json').subscribe(res => {
this.planets = res.json();
console.log(this.planets);
this.getPlanetsToView(0);
});


And I have this in template:

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


I have got problem:
Photo

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

Answer

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