【发布时间】:2017-03-19 13:37:03
【问题描述】:
我正在尝试在我的模板中显示来自控制器中 json 的数据。
我发现的所有替代方案都是指使用ngFor,但我不想迭代所有项目,因为我只想显示其中一个。
getServicio(servicioId: number) {
let getServicio = 'services?id=' + servicioId;
this.http.getRequest(getServicio) //returns a json
.then(
res => {
this.services = res[0];
}
)
.catch(
error => console.log(error)
);
}
在模板中我简单地写:
{{services.id}}
它给了我一个错误:
无法读取未定义的属性“id”
没有其他方法可以吗?或者以另一种方式,将所有数据传递给模板并使用如下索引进入数组:
{{services[0].id}}
提前致谢!
【问题讨论】:
-
服务未定义,但尚未收到 HTTP 响应。使用 ngIf 避免在未定义时显示它,或使用
services?.id。顺便说一句,如果它应该是一个单一的服务,你为什么将它命名为services。为什么 getRequest 会返回一个数组,因为您传递的是要检索的唯一对象的 ID?
标签: angular ionic2 angular2-template