如何用Ionic Storage在HTML展示SQLite存储物品(Ionic3/Angular5/Cordova)
在Ionic中展示存储在SQLite(Ionic Storage)里的物品
没问题,我来一步步帮你实现把存在Ionic Storage里的物品展示到HTML页面上,核心逻辑就是先从Storage中读取数据并处理成可用的数组,再用Angular的指令渲染到页面,具体步骤如下:
1. 在组件中获取存储的物品数据
首先,你需要在对应的组件TS文件里编写逻辑,从Storage中读取所有以item 开头的键值对,解析成可直接使用的对象数组。
假设你的组件是ItemsPage,代码示例如下:
import { Component, OnInit } from '@angular/core'; import { Storage } from '@ionic/storage-angular'; @Component({ selector: 'app-items', templateUrl: './items.page.html', styleUrls: ['./items.page.scss'], }) export class ItemsPage implements OnInit { // 用来存储从Storage读取到的物品列表 storedItems: any[] = []; constructor(private storage: Storage) { // Ionic 6+需要先初始化Storage this.initStorage(); } async initStorage() { await this.storage.create(); } ngOnInit() { // 页面初始化时加载存储的物品 this.loadStoredItems(); } async loadStoredItems() { // 获取Storage中所有的键 const allKeys = await this.storage.keys(); // 筛选出我们存储的物品键(以"item "开头) const itemKeys = allKeys.filter(key => key.startsWith('item ')); // 遍历每个键,取出对应的数据并解析JSON this.storedItems = await Promise.all( itemKeys.map(async (key) => { const itemJson = await this.storage.get(key); return JSON.parse(itemJson); }) ); // 可选:按ID排序,保证物品顺序和你最初存储的一致 this.storedItems.sort((a, b) => parseInt(a.id) - parseInt(b.id)); } }
2. 在HTML中渲染物品列表
有了storedItems数组后,就可以用Angular的*ngFor指令在HTML里循环渲染每个物品了,用Ionic的原生列表组件展示会更贴合框架风格:
<ion-header> <ion-toolbar> <ion-title>存储的物品</ion-title> </ion-toolbar> </ion-header> <ion-content class="ion-padding"> <ion-list> <!-- 循环遍历storedItems数组,渲染每个物品 --> <ion-item *ngFor="let item of storedItems"> <ion-label> <h2 class="ion-text-bold">{{ item.name }}</h2> <p>{{ item.description }}</p> <small class="ion-text-muted">ID: {{ item.id }}</small> </ion-label> </ion-item> </ion-list> <!-- 没有物品时显示提示 --> <div *ngIf="storedItems.length === 0" class="ion-text-center ion-margin-top"> <p>暂无存储的物品</p> </div> </ion-content>
额外注意事项
- Ionic Storage的操作都是异步的,一定要用
async/await或者Promise处理,避免出现数据还没读取完就渲染页面的情况。 - 如果后续有新增、删除物品的操作,记得在操作完成后调用
this.loadStoredItems()刷新列表。 - 确保你已经在
app.module.ts里正确导入并配置了IonicStorageModule,否则Storage服务无法正常使用。
内容的提问来源于stack exchange,提问作者jamesharvey
相关产品推荐
相关产品推荐

