模板中的 Ionic2 数组访问
Ionic2 array access in template
我正在尝试在我的模板中显示来自控制器中 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}}
它给我一个错误:
Cannot read property 'id' of undefined
没有其他方法吗?或者以另一种方式,将所有数据传递给模板并进入具有如下索引的数组:
{{services[0].id}}
提前致谢!
问题是您试图在数据 (services.id
) 到达之前显示它(http 请求是异步的)- 这意味着 services.id
在模板是 undefined
呈现。最简单的解决方案是使用 安全导航运算符 (?
) 到 "protect" 您的模板,直到数据到达:
{{services?.id}}
您还可以使用 ngIf
指令,这样您要显示 services
的模板部分在定义 services
之前不会呈现:
<div *ngIf="services">
{{services?.id}}
</div>
我正在尝试在我的模板中显示来自控制器中 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}}
它给我一个错误:
Cannot read property 'id' of undefined
没有其他方法吗?或者以另一种方式,将所有数据传递给模板并进入具有如下索引的数组:
{{services[0].id}}
提前致谢!
问题是您试图在数据 (services.id
) 到达之前显示它(http 请求是异步的)- 这意味着 services.id
在模板是 undefined
呈现。最简单的解决方案是使用 安全导航运算符 (?
) 到 "protect" 您的模板,直到数据到达:
{{services?.id}}
您还可以使用 ngIf
指令,这样您要显示 services
的模板部分在定义 services
之前不会呈现:
<div *ngIf="services">
{{services?.id}}
</div>