如何从数据数组获取对象数组值?下面是我的代码
组件
FmtNews(mediasource) {
let body = mediasource;
console.log("Test body:" +body)
this.commonService.getTopNews(body)
.subscribe((res) => {
if (res['status'].code === 102) {
// this.headerService.isLoading = false;
console.log(res['data'])
}
});
}
console.log(res['data'])
出现了这样的例子。
(4)[..]
0: Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)
1:Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)
2:Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)
3:Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)
我的问题是..,我如何获取对象中的数据以显示在 HTML 页面
中HTML
<div class="media">
<img class="mr-3" src="..." alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0">title here</h5>
<span>url here</span>
<div>
contents here
</div>
</div>
</div>
答案 0 :(得分:3)
只需声明一个局部变量并将响应分配给该变量即可在HTML中使用:
list: any[] = []; <-- here
FmtNews(mediasource) {
let body = mediasource;
console.log("Test body:" +body)
this.commonService.getTopNews(body)
.subscribe((res) => {
if (res['status'].code === 102) {
this.list = res['data'];
console.log(res['data'])
}
});
}
HTML:
<div *ngFor="let obj of list">
{{obj.mediaSource}}
</div>
OR
如果您想显示mediaSource
作为标题,则:
<div>{{ list[0]?.mediaSource }}</div>
将显示第一项的mediaSource属性!
编辑
<div class="media" *ngFor="let obj of list">
<img class="mr-3" src="..." alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0">{{ obj.mediaSource }}</h5>
<span>{{ obj.pageUrl}}</span>
<div>
{{ obj.contents}}
</div>
</div>
</div>
答案 1 :(得分:1)
将数据存储到变量this.data=res['data']
在您的HTML中,
<div class="media">
<img class="mr-3" src="..." alt="Generic placeholder image">
<div class="media-body" *ngFor="let obj of data">
<h5 class="mt-0">{{obj.mediaSource}}</h5>
<span>{{obj.pageUrl}}</span>
<div>{{obj.contents}}</div>
</div>
</div>