Angular 18 獨立應用程式和 CapacitorJS 中的 SQLite 集成
本教學介紹如何將 SQLite 整合到使用獨立元件和訊號的 Angular 18 應用程式中。我們將使用 @capacitor-community/sqlite 外掛程式為 Android 和 iOS 平台啟用 SQLite 功能。
先決條件
確保您已安裝以下軟體:
- Node.js 和 npm
- CapacitorJS
- 具有獨立組件和訊號的 Angular 18
第 1 步:安裝所需的軟體包
執行以下命令來安裝必要的依賴項:
npm install @capacitor-community/sqlite npx cap sync
這些指令安裝 SQLite 外掛程式並將變更與本機平台同步。
步驟2:建立資料庫服務
資料庫邏輯將封裝在服務中,以提高可維護性。
// 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; } } } </void></any></void></void></void>
第三步:在根元件中初始化資料庫服務
在應用程式的根元件中,初始化 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(); } }
筆記
- 連線一致性:確保使用 checkConnectionsConsistency() 檢查連線一致性,以避免重複的連線錯誤。
- 單例服務:使用Angular的@Injectable和providedIn:'root'來確保DatabaseService是單例。
- 在兩個平台上進行測試:始終在 Android 和 iOS 裝置上測試您的實作。
結論
透過這些步驟,您已成功使用 CapacitorJS 將 SQLite 整合到 Angular 18 獨立應用程式中。此實作可確保連線一致性並將資料庫操作封裝在可重複使用服務中。
以上是Ionic:Angular CapacitorJS 和 SQLite的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

WebStorm Mac版
好用的JavaScript開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中