大家好,有人能帮我把包含products对象的JSON放到角HTML中吗?我让它在控制台中工作(见下图),但我不知道如何用HTML显示产品数据。这就是我做的代码。
我的app.component.html是
`<div *ngFor="let product of data.products" style="text-align:center">
<div>
{{ product.id }}
{{ product.product_name }}
</div>` 我的app.component.ts是
export class AppComponent {
title = 'Isham-ColdBanana';
public data:any = []
constructor(private http: HttpClient) {
}
getData(){
const url ='https://my-json-server.typicode.com/TomSearle/cb-devtest-api/db'
this.http.get(url).subscribe((res)=>{
this.data = res
console.log(this.data)
})
}
ngOnInit(){
this.getData();
}
}

发布于 2022-09-15 01:13:51
试着做这样的事情:
`<div *ngFor="let product of data.products[0]" style="text-align:center">
<div>
{{ product.id }}
{{ product.product_name }}
</div>` 发布于 2022-09-15 06:10:20
解决方案有效,但现在我在控制台上看到了这个错误.为了绕开那个错误?
core.mjs:7643 ERROR TypeError: Cannot read properties of undefined (reading '0')
at AppComponent_Template (app.component.html:69:62)
at executeTemplate (core.mjs:12114:9)
at refreshView (core.mjs:11977:13)
at refreshComponent (core.mjs:13073:13)
at refreshChildComponents (core.mjs:11767:9)
at refreshView (core.mjs:12027:13)
at renderComponentOrTemplate (core.mjs:12094:9)
at tickRootContext (core.mjs:13215:13)
at detectChangesInRootView (core.mjs:13241:5)
at RootViewRef.detectChanges (core.mjs:13757:9)发布于 2022-09-15 11:45:55
知道了,我把app.component.ts修改成了public data:any = {locations:[], products:[]}
https://stackoverflow.com/questions/73723127
复制相似问题