[英]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. 我对Angular并不陌生,我很轻松地遵循了《英雄之旅》教程,并使整个应用程序正常工作。 I have now started a new project, which is just getting data from the Strava API to display it.
我现在已经开始一个新项目,该项目只是从Strava API获取数据以显示它。
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. 到目前为止,我已经设法获取了一系列活动并将其显示出来,它们以对象数组的形式出现,并且我只是与下面的第一张图片做相同的事情,只是使用了不同的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. 当我尝试招募运动员时,API用一个JSON对象响应,我可以通过在
getDataFromURL
函数内部输出response.json()
来看到。
When I attempt to output onto the page using {{athlete.id}}
I just get a Cannot read property 'id' of undefined
error. 当我尝试使用
{{athlete.id}}
输出到页面上时,我只是得到了Cannot read property 'id' of undefined
错误。 I have tried to change a bunch of things to get to this stage but just can't 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>
Use 采用
{{athlete?.id}}
to make the code null
-safe for async loaded data. 为了让代码
null
的异步加载的数据-保险箱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.