R.Boguslawski
R.Boguslawski

Reputation: 35

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.

Upvotes: 2

Views: 2445

Answers (1)

Riscie
Riscie

Reputation: 4649

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

The ? is called elivs operator and is used to safe guard against undefined references in view templates. Read more here:

Upvotes: 3

Related Questions