[英]Angular 2 not displaying data from HTTP
I'm doing an HTTP request using Angular 2, but the results aren't being displayed. 我正在使用Angular 2执行HTTP请求,但未显示结果。 I have the following service: 我有以下服务:
getData() {
return this.http.get(this.api)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
Here's my AppComponent
: 这是我的AppComponent
:
info: any;
error: any;
constructor(private appService: AppService) {}
getData() {
this.appService
.getData()
.then(response => this.info = response)
.catch(error => this.error = error);
}
ngOnInit() {
this.getData();
}
On my template, I'm calling {{info.fields.id}}
but it gives me an error: ORIGINAL EXCEPTION: TypeError: Cannot read property 'data' of undefined
. 在我的模板上,我正在调用{{info.fields.id}}
但它给了我一个错误: ORIGINAL EXCEPTION: TypeError: Cannot read property 'data' of undefined
。
Any hints on what I'm doing wrong? 关于我在做什么错的任何提示吗?
I also created a Plunker to reproduce this issue. 我还创建了一个Plunker来重现此问题。
Try using the safe navigation (Elvis) operator in your template, for example fruit: {{info?.data?.fruit}}
. 尝试在模板中使用安全导航(Elvis)运算符,例如fruit: {{info?.data?.fruit}}
。 You can find more information about the safe operator here 您可以在此处找到有关安全操作员的更多信息
This is needed because your service is returning a promise. 这是必需的,因为您的服务正在兑现承诺。 In the getData() method of your controller, you are using that promise and with .then() you're setting the info property on the controller. 在控制器的getData()方法中,您正在使用该诺言,并通过.then()在控制器上设置info属性。 The problem is that the view is rendering before your promise is completely resolved. 问题在于视图在您的诺言完全解决之前就已呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.