[英]How display data from json array in angular 7
I have a json data set with arrays from my ASP.net Core web api, i want to show that data in angular html page. 我有一个来自ASP.net Core Web API的带有数组的json数据集,我想在有角度的html页面中显示该数据。 can you help me.
你能帮助我吗。
angular 7 cli 角度7 cli
ngOnInit() {
this.serverService.getAllProductData().subscribe(
(response:Response)=>{
let result = response;
console.log(result);
}
);
}
[
{
"productId": 1,
"productName": "product 1",
"productPrice": 500
},
{
"productId": 2,
"productName": "product 2",
"productPrice": 1000
},
{
"productId": 3,
"productName": "product 3",
"productPrice": 2000
},
{
"productId": 4,
"productName": "PRODUCT 4",
"productPrice": 3000
},
{
"productId": 5,
"productName": "produt 5",
"productPrice": 10000
}
]
You need to iterate over the items using ngFor 您需要使用ngFor遍历项目
<ul>
<li *ngFor="let resultObj of result">
{{ resultObj.productName}}
</li>
</ul>
also declare the result globally in TS outside ngOnInit. 还可以在ngOnInit之外的TS中全局声明结果。
result : any;
ngOnInit() {
this.serverService.getAllProductData().subscribe(
(response:Response)=>{
this.result = response;
console.log(result);
}
);
}
You can use Sajeetharan answer, or try async
pipe with auto unsubscribe from the Observable. 您可以使用Sajeetharan答案,也可以尝试通过Observable自动取消订阅的
async
管道。
public getAllProductData$: Observable<any> = undefined;
ngOnInit() {
this.getAllProductData$ = this.serverService.getAllProductData();
}
and the template: 和模板:
<div *ngIf="(getAllProductData$ | async) as data">
<ul>
<li *ngFor="let item of data">
{{ item.productName}}
</li>
</ul>
</div>
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.