簡體   English   中英

Ionic 2 Toggle使用存儲保存數據

[英]Ionic 2 Toggle save data with Storage

我有一個非常簡單的問題,我正在構建一個應用程序,其中有一個帶有切換輸入的設置頁面,供用戶打開和關閉一些警報。 我的問題是我如何保存切換值,以便當有人關閉應用程序或導航到另一個頁面時,切換狀態不應丟失並且當前切換應以html反映。 目前,我正在使用cordova-sqlite-storage插件存儲toggle值。

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>

頁面

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

storage.ready() ,應在類中設置AlertOn200和/或toggleStatus屬性,而不是val屬性。 這應該將切換設置為存儲中的值。

編輯:我添加了下面的一些代碼,我已經對其進行了測試和工作。 離子開關的初始值由存儲中的值設置,如果您手動切換離子開關,則存儲中的值會更改。

我建議刪除ion-toggle組件中的[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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM