ionic android 本地存储,ionic2/3本地数据存储storage
时间: 2024-01-05 19:02:17 浏览: 176
Ionic提供了一个名为`Ionic Storage`的基于Promise的本地存储解决方案,可以用于在Ionic应用程序中存储和检索键值对数据。
在Ionic 2/3中,您可以通过以下步骤使用Ionic Storage:
1. 安装Ionic Storage:
```
npm install --save @ionic/storage
```
2. 在`app.module.ts`文件中导入`IonicStorageModule`并将其添加到`imports`数组中:
```
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: [ MyApp ],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [ MyApp ],
providers: []
})
export class AppModule {}
```
3. 在需要使用本地存储的页面或服务中导入`Storage`:
```
import { Storage } from '@ionic/storage';
```
4. 在构造函数中注入`Storage`:
```
constructor(private storage: Storage) {}
```
5. 使用`Storage`的`set`和`get`方法来存储和检索数据:
```
this.storage.set('name', 'John');
this.storage.get('name').then((name) => {
console.log('Name is', name);
});
```
6. 如果需要使用`async/await`语法,则可以在方法前加上`async`关键字,并使用`await`关键字等待结果:
```
async saveData() {
await this.storage.set('age', 30);
const age = await this.storage.get('age');
console.log('Age is', age);
}
```
注意:Ionic Storage支持多种本地存储引擎,包括LocalStorage、IndexedDB和SQLite。默认情况下,Ionic Storage使用LocalStorage作为存储引擎,但您可以通过在`forRoot`方法中传递配置选项来更改存储引擎。例如,如果您想使用SQLite作为存储引擎,可以使用以下代码:
```
IonicStorageModule.forRoot({
name: '__mydb',
driverOrder: ['sqlite', 'indexeddb', 'websql']
})
```
阅读全文
相关推荐
















