LoginSignup
5
3

More than 5 years have passed since last update.

IonicのStorageプラグインの使い方

Last updated at Posted at 2017-08-16

はじめに

公式ページ
参考ページ

Ionicでデータを保存できる[* Storage]インターフェース。

保存方法はキー・バリューの形式であり、バリューにはJSONをそのまま格納できる。

モバイル端末上で動かす際にはSQLiteを内部的に用いるため、CordovaのSQLiteプラグインをインストールしておく必要があります。

なので、公式のやり方にしたがって使用準備をします。

また、

ストレージのエンジン (ドライバー) としては、スマートフォン上で実行する場合は SQLite を優先的に利用し、 Web のコンテキストでは IndexedDB、WebSQL、localstorage の順で利用します。

なので、今回は特別にStorageを指定せず導入してみます。
Storageの指定方法はページの一番下に記述します。

準備

$ ionic cordova plugin add cordova-sqlite-storage

$ npm install --save @ionic/storage

app.module.ts
 import { IonicStorageModule } from '@ionic/storage';

 @NgModule({
   declarations: [
     // ...
   ],
   imports: [      
     // ...
     IonicStorageModule.forRoot()
   ],
   // ...
 })
 export class AppModule {}

使用方法

Storageを使いたい場所でInjectすれば使えます。
ここではoverwatch-jsというAPIを使用して取得したデータをストレージに格納、使用しております。

search.ts
 ...
 import { Storage } from '@ionic/storage';

 @Component({
   ...
 })
 export class SearchPage {
   constructor(... private storage: Storage) {
     ...
   }

   // 検索を行う
   getPlayerInfo(playerIdFirstPart, playerIdSecondPart) {
    ...
     let instance: SearchPage = this;
     // overwatch-jsの詳細情報取得メソッド
     overwatchJs.getAll(this.platform, this.region, playerId).then(
       (data) => {         
         // storage.set()でストレージにkey, value(JSON)の形式で格納する
         instance.storage.set(data.profile.nick, data);
         console.log(data.profile.nick); 
         ...
       }, (reason) => {
         ...
       }
     );
   }
   ...
 }
home.ts
 ...
 import { Storage } from '@ionic/storage';

 @Component({
   ...
 })
 export class HomePage {

   items;

   constructor(public navCtrl: NavController, private storage: Storage) {
     this.initializeItems();
   }

   initializeItems() {
     this.items = new Array();
     // storage.forEach()でstorageに格納されているvalueとkeyの組み合わせをまわす
     this.storage.forEach((value, key) => {
       let userIdIndex = value.profile.url.lastIndexOf('/');
       let regionIndex = value.profile.url.lastIndexOf('/', userIdIndex - 1);
       let platformIndex = value.profile.url.lastIndexOf('/', regionIndex - 1);
       this.items.push({
         'userInfo': value,
         'userId': value.profile.url.slice(userIdIndex + 1),
         'region': value.profile.url.slice(regionIndex + 1, userIdIndex),
         'platform': value.profile.url.slice(platformIndex + 1, regionIndex)
       })
     });
     console.log(this.items);
   }
 }

※Storageの指定 公式引用

app.module.ts
 import { IonicStorageModule } from '@ionic/storage';

 @NgModule({
   declarations: [...],
   imports: [
     IonicStorageModule.forRoot({
       name: '__mydb',
          driverOrder: ['indexeddb', 'sqlite', 'websql']
     })
   ],
   bootstrap: [...],
   entryComponents: [...],
    providers: [...]
 })
 export class AppModule { } 
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3