如何将数据数组对象保存到Ionic SQLite Storage(TypeScript、Angular 5、Ionic 3)
嘿,我来帮你搞定用Ionic SQLite Storage把这些选项存入收藏列表的事儿!
实现Ionic SQLite Storage收藏列表功能
首先,先确保你已经装好必要的依赖:
ionic cordova plugin add cordova-sqlite-storage npm install @ionic-native/sqlite-storage
然后记得在app.module.ts里导入SQLiteStorage模块,并添加到providers数组中,这样整个项目都能调用它。
接下来咱们可以写一个专门的收藏服务(比如favorites.service.ts),把核心功能都封装在这里,代码更整洁:
1. 初始化数据库与创建收藏表
先注入SQLiteStorage,然后初始化数据库,创建一个favorites表来存储你的选项数据:
import { Injectable } from '@angular/core'; import { SQLiteStorage } from '@ionic-native/sqlite-storage/ngx'; @Injectable({ providedIn: 'root' }) export class FavoritesService { private db: any; constructor(private storage: SQLiteStorage) { this.initDB(); } async initDB() { this.db = await this.storage.create({ name: 'favorites.db', location: 'default' }); // 创建表,字段对应你options对象的属性 await this.db.executeSql(`CREATE TABLE IF NOT EXISTS favorites ( id TEXT PRIMARY KEY, name TEXT, website TEXT, about TEXT )`, []); } }
2. 添加收藏功能
写一个方法接收单个选项对象,把它插入到收藏表里。这里用id当主键,避免重复添加同一选项:
async addToFavorites(option: any) { // 先检查这个选项是否已经在收藏里了 const existing = await this.db.executeSql('SELECT * FROM favorites WHERE id = ?', [option.id]); if (existing.rows.length === 0) { await this.db.executeSql(`INSERT INTO favorites (id, name, website, about) VALUES (?, ?, ?, ?)`, [option.id, option.name, option.website, option.about]); return true; // 添加成功 } return false; // 已经收藏过啦,不用重复加 }
3. 获取所有收藏内容
如果需要展示用户的收藏列表,写个查询方法把所有数据取出来:
async getFavorites() { const result = await this.db.executeSql('SELECT * FROM favorites', []); const favorites = []; for (let i = 0; i < result.rows.length; i++) { favorites.push(result.rows.item(i)); } return favorites; }
4. 取消收藏功能
用户想移除收藏的话,写个删除方法:
async removeFromFavorites(optionId: string) { await this.db.executeSql('DELETE FROM favorites WHERE id = ?', [optionId]); }
在页面组件里调用服务
比如在展示选项列表的页面里,注入咱们的收藏服务和你的DataProvider,就能实现收藏/取消的操作了:
import { Component } from '@angular/core'; import { FavoritesService } from '../services/favorites.service'; import { DataProvider } from '../providers/data'; // 你的data.ts提供者 @Component({ selector: 'app-options', templateUrl: './options.page.html', styleUrls: ['./options.page.scss'], }) export class OptionsPage { options: any[]; constructor( private dataProvider: DataProvider, private favoritesService: FavoritesService ) { this.options = this.dataProvider.options; } async toggleFavorite(option: any) { const isAdded = await this.favoritesService.addToFavorites(option); if (!isAdded) { await this.favoritesService.removeFromFavorites(option.id); } // 这里可以加个Toast提示用户操作结果,比如"已收藏"/"已取消收藏" } }
额外小技巧
如果需要判断某个选项是否已收藏,可以加个辅助方法:
async isFavorite(optionId: string) { const result = await this.db.executeSql('SELECT * FROM favorites WHERE id = ?', [optionId]); return result.rows.length > 0; }
这样你就能轻松把data.ts里的选项存入SQLite收藏列表啦!
内容的提问来源于stack exchange,提问作者jamesharvey
相关产品推荐
相关产品推荐

