本教學介紹如何將 SQLite 整合到使用獨立元件和訊號的 Angular 18 應用程式中。我們將使用 @capacitor-community/sqlite 外掛程式為 Android 和 iOS 平台啟用 SQLite 功能。
確保您已安裝以下軟體:
執行以下命令來安裝必要的依賴項:
npm install @capacitor-community/sqlite npx cap sync
這些指令安裝 SQLite 外掛程式並將變更與本機平台同步。
資料庫邏輯將封裝在服務中,以提高可維護性。
// src/app/services/database.service.ts import { Injectable } from '@angular/core'; import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite'; @Injectable({ providedIn: 'root', }) export class DatabaseService { private sqlite: SQLiteConnection; private db: SQLiteDBConnection | null = null; constructor() { this.sqlite = new SQLiteConnection(CapacitorSQLite); } async initializeDatabase(): Promise<void> { try { // Check connection consistency const retCC = (await this.sqlite.checkConnectionsConsistency()).result; // Check is connected const isConnection = (await this.sqlite.isConnection('appDB', false)).result; if (!isConnection && !retCC) { // Create a new connection this.db = await this.sqlite.createConnection('appDB', false, 'no-encryption', 1, false); await this.db.open(); await this.createTables(); } else { // Retrieve existing connection this.db = await this.sqlite.retrieveConnection('appDB', false); await this.db.open(); } } catch (error) { console.error('Error initializing the database:', error); } } private async createTables(): Promise<void> { if (!this.db) throw new Error('Database connection is not open'); const createTableQuery = ` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL ); `; await this.db.execute(createTableQuery); } async addUser(name: string, age: number): Promise<void> { if (!this.db) throw new Error('Database connection is not open'); const insertQuery = `INSERT INTO users (name, age) VALUES (?, ?);`; await this.db.run(insertQuery, [name, age]); } async getUsers(): Promise<any[]> { if (!this.db) throw new Error('Database connection is not open'); const result = await this.db.query('SELECT * FROM users;'); return result.values || []; } async closeDatabase(): Promise<void> { if (this.db) { await this.sqlite.closeConnection('appDB'); this.db = null; } } }
在應用程式的根元件中,初始化 DatabaseService。
// src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { DatabaseService } from './services/database.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent implements OnDestroy, AfterViewInit { constructor(private databaseService: DatabaseService) {} // Important: Initialize the database connection when the component is created async ngAfterViewInit() { await this.databaseService.initializeDatabase(); } // Important: Close the database connection when the component is destroyed async ngOnDestroy() { await this.databaseService.closeDatabase(); } }
您現在可以在任何元件中使用DatabaseService來執行CRUD操作。
// src/app/components/user-list/user-list.component.ts import { Component, OnInit } from '@angular/core'; import { DatabaseService } from '../../services/database.service'; @Component({ selector: 'app-user-list', templateUrl: './user-list.component.html', }) export class UserListComponent implements OnInit { users: any[] = []; constructor(private databaseService: DatabaseService) {} async ngOnInit() { await this.databaseService.addUser('Max Mustermann', 25); await this.databaseService.addUser('Erika Musterfrau', 30); this.users = await this.databaseService.getUsers(); } }
透過這些步驟,您已成功使用 CapacitorJS 將 SQLite 整合到 Angular 18 獨立應用程式中。此實作可確保連線一致性並將資料庫操作封裝在可重複使用服務中。
以上是Ionic:Angular CapacitorJS 和 SQLite的詳細內容。更多資訊請關注PHP中文網其他相關文章!