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));
}
}
source to share
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.
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}}
source to share
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.
source to share