---
title: "Ionic2的数据存储"
author: "maxer025"
date: "2017-12-01T12:21:53Z"
tags: []
categories: ["移动开发"]
slug: "ionic2"
draft: false
lastmod: "2017-12-01T12:21:53Z"
id: 2401542
url: "https://maxer025.iteye.com/blog/2401542"
---

Ionic2的数据存储
翻译 2017年03月29日 14:50:51

当在一个原生app词法环境下，一般优先使用SQLite,因为它是使用最广泛的稳定的文档型数据库之一，它也避免了一些诸如localstorage和IndexedDB的一些困境，比如系统在磁盘空间不够的时候会清除数据。

如果你是在web中或者web app中运行的话，一般倾向于使用IndexedDB,WebSQL,以及localstorage.

假如你使用的是SQLite,首先你得安装 cordova-sqlite-storage 插件。

cordova plugin add cordova-sqlite-storage --save

    1

然后npm按照包：

npm install --save @ionic/storage

    1

之后import这个插件，在你的NgModule的imports的数组中，将模块注入进app里。

下面就是一个实例：

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: ,
  imports: ,
  bootstrap: ,
  entryComponents: ,
  providers: 
})
export class AppModule {}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

这样，你如果在那个component中需要使用数据库的时候你就可以通过import进行注入：

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);
       })
     });
  }
}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    配置存储

开发者可以使定义好的存储引擎优先级配置存储引擎，或者自定义配置选项到localForage上。

注意：任何自定义的配置都会被合并到默认配置上。

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: ...,
  imports: 
    })
  ],
  bootstrap: ...,
  entryComponents: ...,
   providers: 
})
export class AppModule {}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

下面就是数据库的使用方法：

    driver 获取驱动名称
    ready()反应存储
    get(key)获取对应数据
    set(key,value) 设置数据
    remove(key)删除对应数据
    clear()清除所有数据
    length()获取数据长度
    keys()获取键
    forEach(callback) 遍历数据库