【发布时间】:2017-05-03 15:09:34
【问题描述】:
我认为我在插值方面遗漏了一些东西。 我使用 http.get 作为我的服务来获取数据
post.service 代码:
getPosts() {return this._http.get(this._Url + 'events').map((_response: Response) => {
const data = _response.json()
return _response.json();
});
在我的组件上,我运行以下代码将响应传递给 res 数组 组件代码:
getdata(){this._postService.getPosts()
.subscribe(
posts => {
posts.forEach(posts => {
this.res.push(
new event(
posts.field_event_title[0].value,
posts.field_event_price[0].value,
"test loc"
)
)
});
}
,
(error) => console.log(error, "error from observable")
);
console.log(this.res, "res after subs")
}
HTML代码:
<div class="row" *ngFor="let post of res">
Title: {{post.title}} <br>
Price: {{post.price}} <br>
Location:{{post.location}}
</div>
我的问题是使用 *ngFor 我可以显示我的数据。但我只想阅读 1 篇文章。资源[0] .title。当我在 html {{ res[0].title }} 中使用时,我收到错误“无法读取未定义的属性“title”。对此有任何帮助!?最后我想要的是能够使用数组res 在 dom 中显示数据
【问题讨论】:
-
因为你的数组开始是空的,你需要用
*ngIf="res.length > 0"包围它 -
试试
res[0]?.title这是异步问题,所以使用安全导航运算符:) -
或者照 AJT_82 说的做,甚至使用async pipe
标签: angular typescript