Martyn Rushton Martyn Rushton - 2 months ago 7
Javascript Question

Angular: Object showing as undefined in html even though it has data in the service

I am pretty new to angular, I managed to follow the Tour of Heroes tutorial pretty easily and got the entire application working. I have now stared a new project, which is just getting data from the Strava API to display it.

So far I have managed to get a list of activities and display them, they come in as an array of Objects, and I just do the same thing as the first image below, only with a different URL.

When I try to get an athlete, the API is responding with a JSON object, which I can see with by outputting response.json() inside the getDataFromURL function.

When I attempt to output onto the page using

{{athlete.id}}
I just get a
Cannot read property 'id' of undefined
error. I have tried to change a bunch of things to get to this stage but just cant get it to work. Any help would be appreciated.

//getAthlete and getDataFrom URL from the service
/* Recieve data from a given URL over jsonp */
private getDataFromURL(url: string): Promise<any> {
return this.jsonp.get(url)
.toPromise()
.then(response => response.json())
.catch(this.handleError)
}

/* Get details of a single athelete */
getAthlete(): Promise<any> {
let url = 'https://www.strava.com/api/v3/athlete?per_page=1&access_token=' + this.accessToken + '&callback=JSONP_CALLBACK';
return this.getDataFromURL(url)

}





//getAthlete from the component

athlete: Object

getAthlete(): void {
this.stravaService.getAthlete().then(athlete => this.athlete = athlete)
}

ngOnInit(): void {
this.getAthlete()
}





//Here is the html code to try and put athelete.id on the page

<span class="id">{{athlete.firstname}}</span>

Answer

Use

{{athlete?.id}}

to make the code null-safe for async loaded data.