如何从数据数组获取对象数组值?下面是我的代码
零件
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>
只需声明一个局部变量并将响应分配给该变量即可在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>
要么
如果要显示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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句