本文为原创文章,转载请标明出处html
Storage能够很容易的存储键值对和JSON对象。Storage在底层使用多种存储引擎,根据运行平台选择最佳的存储方式。
当运行在Native模式时,Storage将优先使用SQLite。
当运行在Web中或做为PWA应用时,Storage将根据你肯定的优先级使用IndexedDB、WebSQL或localstorage。git
若是须要使用SQLite,先安装 Cordova-sqlite-storage
,命令行输入github
ionic cordova plugin add cordova-sqlite-storage npm install --save @ionic-native/sqlite
在 ./src/app/app.module.ts
中添加web
import { IonicStorageModule } from '@ionic/storage'; @NgModule({ declarations: [...], imports: [ ..., IonicStorageModule.forRoot() ], bootstrap: [...], entryComponents: [...], providers: [...] }) export class AppModule { }
配置存储引擎优先级,在 ./src/app/app.module.ts
中添加sql
import { IonicStorageModule } from '@ionic/storage'; @NgModule({ declarations: [...], imports: [ ..., IonicStorageModule.forRoot({ name: 'myApp', driverOrder: ['sqlite', 'indexeddb', 'websql'] }) ], bootstrap: [...], entryComponents: [...], providers: [...] }) export class AppModule { }
import {Injectable} from '@angular/core'; import {Storage} from '@ionic/storage'; @Injectable() export class UserData { constructor(public storage: Storage) { } setUsername(username: string): void { this.storage.set('username', username); } getUsername(): Promise<string> { return this.storage.get('username').then((value) => { return value; }); } }
更多可详见npm
若有不当之处,请予指正,谢谢~bootstrap