Ionic3--数据存储

1.使用sqlite

cordova plugin add cordova-sqlite-storage --save

npm install --save @ionic/storage (本地存储)

npm install --save @ionic-native/sqlite(sqlite)

2.之后import这个插件,在你的NgModuleimports的数组中,将模块注入进app里。

import { IonicStorageModule } from '@ionic/storage';

@NgModule({

  declarations: [ // ... ],

  imports: [

    IonicModule.forRoot(MyApp),

    IonicStorageModule.forRoot() //就这里

  ],

  bootstrap: [IonicApp], entryComponents: [ // ... ],

  providers: []

})

export class AppModule {}

3.在模块中使用

import { Storage } from '@ionic/storage';

export class MyApp {

  constructor(storage: Storage) {

    storage.ready().then(() => {

      // set a key/value

      storage.set('name', 'Max');

       // Or to get a key/value pair

      storage.get('age').then((val) => {

        console.log('Your age is', val);

       })

     });

   }

}

4.配置存储

开发者可以使定义好的存储引擎优先级配置存储引擎,或者自定义配置选项到localForage上。

注意:任何自定义的配置都会被合并到默认配置上。

import { IonicStorageModule } from '@ionic/storage';

@NgModule({

  declarations: ...,

   imports: [

    IonicStorageModule.forRoot({

      name: '__mydb',

        driverOrder: ['indexeddb', 'sqlite', 'websql']

     })

  ],

  bootstrap: ...,

  entryComponents: ...,

  providers: [] })

export class AppModule {}

5.

下面就是数据库的使用方法:

  1. driver 获取驱动名称
  2. ready()反应存储
  3. get(key)获取对应数据
  4. set(key,value) 设置数据
  5. remove(key)删除对应数据
  6. clear()清除所有数据
  7. length()获取数据长度
  8. keys()获取键
  9. forEach(callback) 遍历数据库
原文地址:https://www.cnblogs.com/lvshoutao/p/8422538.html