Mixer94us
Mixer94us

Reputation: 1

ERROR TypeError: Cannot read property 'Name' of undefined after get Json

I have a problem with my application in angular2. I need to connect to api to retrieve records to my Persons [] class. I want to use the second method to get people with individual id. I do the same way as in the tutorial on the Angular site but unfortunately I still have a fault

ERROR TypeError: Cannot read property 'Name' of undefined

This is my service

getPersons(): Promise<Person[]> {
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
    var token = currentUser.token;

    let headers = new Headers({ 'Authorization': 'Bearer ' + token })
    let options = new RequestOptions({ headers: headers });
    return this.http.get(this.QuestionsUrl, options)
        .toPromise()
        .then(response => response.json() as Person[]);
}
getPerson(id: number): Promise<Person> {
    return this.getPersons().then(persons => persons.find(person => person.Id === id));
}

My component:

export class PersonsComponent implements OnInit {
activePerson: any = {};
model: any = {};

constructor(private personService: PersonService, private route: ActivatedRoute, private location: Location) {

}

ngOnInit(): void {
    this.route.paramMap.switchMap((params: ParamMap) => this.personService.getPerson(+params.get('Id')))
        .subscribe(selected => this.activePerson = selected);


}

}

And html:

<body>

     {{activePerson.Name}}

Upvotes: 0

Views: 1134

Answers (2)

Eliseo
Eliseo

Reputation: 57941

use

 {{activePerson |json}}

to know if you are receiving any data

Upvotes: 0

DeborahK
DeborahK

Reputation: 60528

Try using

{{activePerson?.Name}}

With a question mark.

The issue is that the template attempts to display the value before the data is retrieved. At that point, activePerson is undefined. Hence the error message.

The "?" is called a safe navigation operator. It prevents navigating to the "dot" property (name in this example) unless the object to the left of the question mark has a value.

Upvotes: 1

Related Questions