2017-03-01 16 views
0

私は非常に簡単な質問をしています。私は、ユーザがいくつかの警告をオン/オフするためのトグル入力を持つ設定ページを持っています。私の質問は、トグル値を保存する方法です。誰かがアプリケーションを閉じたり、別のページに移動したりしてトグルステータスが失われたり、現在のトグルがhtmlに反映されたりしないようにします。現時点では、私はコードの値を格納するためにコードバ - sqlite - ストレージプラグインを使用しています。 storage.ready()Ionic 2ストレージでデータを保存する

Page.html

<ion-item> 
    <ion-label>300 Units</ion-label> 
    <ion-toggle [(ngModel)]="AlertOn200" [checked]="toggleStatus" (ionChange)="Change_Toggle_on_200();"></ion-toggle> 
    </ion-item> 

Page.ts

import { Component } from '@angular/core'; 
import { NavController, NavParams } from 'ionic-angular'; 
import { Storage } from '@ionic/storage'; 
@Component({ 
    selector: 'page-page2', 
    templateUrl: 'page2.html' 
}) 
export class Page2 { 
    AlertOn200:any; 
    toggleStatus:any; 
    val:any; 
    constructor(public storage: Storage) {  
    storage.ready().then(() => { 
    // get a key/value pair 
     storage.get('toggleStatus').then((val) => { 
     this.val=val; 
     console.log('Status = ', val); 
     }) 
    }); 
    } 
    Change_Toggle_on_200() { 
    if(this.AlertOn200== true){ 
     this.storage.set('toggleStatus','true');   
     console.log("isAlertOn200 = "+this.toggleStatus); 
    } 
    else{ 
    this.storage.set('toggleStatus','false'); 
    console.log("isAlertOn200 = "+this.toggleStatus); 
    } 
    } 
+0

だから問題は? –

+0

コードが機能しません。別のページに移動して戻ったときにtogglestatusの値は保存されません。私の質問をもう一度読んでください。 – bobin56

+0

は 'storage'プラグインにアクセスするカスタムプロバイダですか? –

答えて

0

あなたのクラスの代わりに、valプロパティにAlertOn200および/またはtoggleStatusプロパティを設定する必要があります。これにより、トグルがストレージ内の値に設定されます。

編集:テストして動作している以下のコードをいくつか追加しました。 イオントグルはストレージの値によって初期値が設定されます。手動でトグルトグルを切り替えると、ストレージの値が変更されます。

Iは、イオントグル・コンポーネントに結合[checked]を取り除く提案し、そのように、toggleStatusにトグルのモデルを設定します:

<ion-toggle [(ngModel)]="toggleStatus" (ionChange)="Change_Toggle_on_200();"></ion-toggle> 

あなたは以下のクラスを実装した場合:

export class Page1 { 
    toggleStatus: any; 

    constructor(public navCtrl: NavController, public storage: Storage) { 
    storage.ready().then(() => { 
     storage.get('toggleStatus').then((val) => { 
     console.log(`Setting status from storage to '${this.toggleStatus}'`); 
     this.toggleStatus = val; // <-- Just set this.toggleStatus to the value from storage, this will make the ion-toggle change value from default to value from storage 
     }) 
    }); 
    } 

    Change_Toggle_on_200() { 
    console.log(`changing toggleStatus to '${this.toggleStatus}'`); 
    this.storage.set('toggleStatus', this.toggleStatus); // <-- note we can just set the current value of this.toggleStatus as this changes with the toggle 
    } 
} 
+0

lemme ask、あなたは関数内で行うのではなく、storage.ready()でトグルイベントを処理できますか?申し訳ありませんが、まだ私には不明です...あなたはコードで説明してください:-) – bobin56

+0

私はいくつかのコードで約20分で応答しようとします – Bryandh

+0

ありがとうたくさんの作品:-)そう、ngModelがあれば[チェック]を使用する必要はありませんか? – bobin56

関連する問題