Ionic3学习笔记(七)Storage

本文为原创文章,转载请标明出处

目录

  1. 简介
  2. 安装
  3. 配置
  4. 使用

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;
    });
  }

}

更多可详见
1. Ionic Storage
2. GitHub - localForage

如有不当之处,请予指正,谢谢~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值