0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Are you accessing the Name property anywhere else?
The error has disappeared but has no value. Empty box
I don't use promises like that ... so I can't help you with that part. You could add some console.log() statements in your code to narrow down where the problem may be with retrieving the data. I could point you to some similar code that uses Observables if that would help.
0

use

 {{activePerson |json}}

to know if you are receiving any data

2 Comments

sorry for stupid question but how can i check that ?
I figured out is possible that you received activePerson.name (in lower case) or activePerson.Nome (in nstead of activePerson.Name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.