如何在Angular5和Ionic3中获取JSON数据并展示产品名称
解决方法:展示API返回的产品名称
你已经成功拿到API的JSON响应啦,接下来只需要调整代码把数据绑定到页面模板上就行,我帮你一步步修改:
第一步:修正TypeScript的数据处理逻辑
你现在的data是object类型,但API返回的response是产品数组,我们需要把它存到一个适合循环的数组变量里,同时修正类型定义:
export class SearchPage { searchQuery: string = ''; items: string[]; // 定义产品数组,用any[]临时替代,也可以后续加接口做类型约束 products: any[] = []; constructor(public navCtrl: NavController, private apiService: ApiService) { this.initializeItems(); } initializeItems() { this.apiService.productsCall().subscribe(response => { if(response['status'] == 200) { // 将API返回的产品数组赋值给products变量 this.products = response['response']; console.log(this.products); // 如果需要保留items用于搜索过滤,可以提取所有产品名称到items this.items = this.products.map(product => product.name); } else if(response['status'] == 500) { console.log(response['error'].sqlMessage); } }); // 硬编码的测试数据可以删除,或者留作默认 fallback // this.items=[ 'Knee', 'Knee Cap' ]; } }
第二步:修改HTML模板循环产品数据
现在模板里循环的是原来的硬编码items数组,改成循环我们从API拿到的products数组,直接绑定产品的name字段:
<ion-grid *ngFor="let product of products"> <ion-row> <ion-col col-2> <img src='../assets/imgs/doctor.png'> </ion-col> <ion-col col-offset-1></ion-col> <ion-col col-9> <!-- 直接显示产品名称 --> {{ product.name }} </ion-col> </ion-row> </ion-grid>
额外优化:添加类型约束(可选)
为了让代码更规范,避免类型错误,你可以定义一个Product接口:
// 在SearchPage类外部定义接口 interface Product { product_id: number; name: string; price: number; weight: number; short_desc: string; long_desc: string; category_id: number; units_in_stock: number; units_on_order: number; discount_available: number; images: string | null; } // 然后把products的类型改成Product[] products: Product[] = [];
这样修改后,页面就能自动渲染API返回的所有产品名称了。如果需要做搜索功能,你可以基于products数组来过滤items变量,实现实时搜索的效果。
内容的提问来源于stack exchange,提问作者nff
相关产品推荐
相关产品推荐

