Can't read property 'name' from undefined angular 4

I am trying to print a value in a component template.

But I am getting the above error Cannot read property 'name' of undefined

I have removed unnecessary content from the code for this question. I want to access the first line of details.

Component file

import {
  Component
} from '@angular/core';
import {
  Person
} from './person';
import {
  getPersonDetailsService
} from './person.service';

@Component({
  selector: 'my-app',
  template: `
      {{data[0].name}}
      `
})
export class AppComponent {
  data: Person[] = [];
  ngOnInit(): void {
    this.getPersonDetailsService.getData()
      .then(data => this.data = data.slice(1, 5));
  }

}

      

+3


source to share


4 answers


I think you should first check if the data is defined when printing in the browser.

{{data[0]?.name}}

      

Since your data is not initially defined, you cannot access its name.

Documentation



Angular's safe navigation operator (?.) Is a free and convenient way of protecting against null and undefined values โ€‹โ€‹in property paths. Here it protects against rendering failure if currentHero is null.

You can also check if a variable is null or not using &&

condition

{{data[0] && data[0].name}}

+13


source


From your error message it seems that data

there is undefined (or empty) - and the error occurs on the line that says

{{data[0].name}}

      



Maybe add console.log(data)

before this to check what's going on

0


source


Try putting this in the constructor instead of ngOnInit:

getPersonDetailsService.getData() ...

      

Also, you need to do some checks inside the template in case the "data" doesn't have length> 0 {{data[0]?.name}}

0


source


The value for "data" is updated after the response is resolved from your getData () service. I am assuming you click on a service and receive data. However, the promise will be resolved after the service returns a response. At the same time, the viewer tries to render the template, and when evaluating the data of expression [0], it does not find any element at 0 because the data has not yet been received from the service. Hence, you are getting an error as the 0th index is undefined.

You have to use the observable here.

0


source







All Articles