本文為原創文章,轉載請標明出處
目錄
- 簡介
- 安裝
- 配置
- 使用
1. 簡介
Storage可以很容易的存儲鍵值對和JSON對象。Storage在底層使用多種存儲引擎,根據運行平台選擇最佳的存儲方式。
當運行在Native模式時,Storage將優先使用SQLite。
當運行在Web中或作為PWA應用時,Storage將根據你確定的優先級使用IndexedDB、WebSQL或localstorage。
2. 安裝
如果需要使用SQLite,先安裝 Cordova-sqlite-storage
,命令行輸入
ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic-native/sqlite
在 ./src/app/app.module.ts
中添加
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: [...],
imports: [
...,
IonicStorageModule.forRoot()
],
bootstrap: [...],
entryComponents: [...],
providers: [...]
})
export class AppModule { }
3. 配置
配置存儲引擎優先級,在 ./src/app/app.module.ts
中添加
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: [...],
imports: [
...,
IonicStorageModule.forRoot({
name: 'myApp',
driverOrder: ['sqlite', 'indexeddb', 'websql']
})
],
bootstrap: [...],
entryComponents: [...],
providers: [...]
})
export class AppModule { }
4. 使用
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;
});
}
}
更多可詳見
如有不當之處,請予指正,謝謝~