Angular服务模块访问SQLite3数据库遇依赖错误求助
问题分析与解决方案
问题根源
你用的sqlite3是Node.js环境专属的数据库库,它依赖Node.js内置的util、fs等模块,但Angular运行在浏览器环境中,浏览器没有这些Node.js专属模块,所以编译时会抛出找不到util的错误。
解决方案
因为Angular前端环境无法直接使用Node.js的sqlite3,必须替换为浏览器/前端兼容的SQLite库,以下分场景给出具体方案:
场景1:纯前端浏览器应用(无需对接设备本地数据库)
推荐使用sql.js——纯JavaScript实现的SQLite,完全运行在浏览器中:
- 安装依赖及类型定义
npm install sql.js npm install @types/sql.js --save-dev
- 在Angular服务中使用示例
import { Injectable } from '@angular/core'; import initSqlJs from 'sql.js'; import { SqlJsStatic } from 'sql.js'; @Injectable({ providedIn: 'root' }) export class DataService { private sql: SqlJsStatic | null = null; private db: any; constructor() { this.initDatabase(); } private async initDatabase() { // 初始化SQLite,可选择加载本地assets中的wasm文件或CDN资源 this.sql = await initSqlJs({ locateFile: file => `assets/${file}` // 建议把sql-wasm.wasm下载到assets目录 }); // 创建内存数据库(如需持久化,可将数据库二进制数据存入localStorage) this.db = new this.sql.Database(); // 创建表(替换为你的业务表结构) this.db.run(`CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name TEXT, value TEXT)`); } // 插入数据示例 addItem(name: string, value: string) { if (!this.db) return; const stmt = this.db.prepare("INSERT INTO items (name, value) VALUES (?, ?)"); stmt.run([name, value]); stmt.free(); } // 查询数据示例 getItems() { if (!this.db) return []; const stmt = this.db.prepare("SELECT * FROM items"); const items: {id: number, name: string, value: string}[] = []; while (stmt.step()) { items.push(stmt.getAsObject()); } stmt.free(); return items; } }
场景2:移动端Angular应用(对接设备本地现有SQLite数据库)
如果你的应用是基于Capacitor的移动端应用,需要访问设备上已有的SQLite文件,使用@capacitor-community/sqlite:
- 安装依赖并同步到原生平台
npm install @capacitor-community/sqlite npx cap sync
- 在Angular服务中连接现有数据库示例
import { Injectable } from '@angular/core'; import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite'; @Injectable({ providedIn: 'root' }) export class DataService { private sqliteConnection: SQLiteConnection; private db: SQLiteDBConnection | null = null; constructor() { this.sqliteConnection = new SQLiteConnection(CapacitorSQLite); this.connectExistingDb(); } private async connectExistingDb() { // 连接设备上已有的数据库文件(替换为你的数据库名) this.db = await this.sqliteConnection.createConnection( 'your-existing-db-name', false, 'no-encryption', 1 ); await this.db.open(); // 测试查询现有数据 const result = await this.db.query('SELECT * FROM your-existing-table'); console.log('现有数据:', result.values); } }
内容的提问来源于stack exchange,提问作者user2975847
相关产品推荐
相关产品推荐

