Ion Toggle not saved - Storage (Ionic)

Asked

Viewed 20 times

-1

Hello, I have a simple problem. I have a list of Toggles in my app. I need that when users check or uncheck Toggle, changes are saved after the application is closed. I am using Storagemodule.

I used this code to add Storage:

ionic cordova plugin add cordova-sqlite-storage

Then I made the inclusions in my app.module.ts

This is my HTML:

<ion-toggle slot="end" color="secondary" [(ngModel)]="Ativar" (ionChange)="Toggle1()"></ion-toggle>

This is my TS:

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

export class Tab1Page {
 
 public Ativar : boolean;



 constructor(public alert: AlertController, public navCtrl: NavController, private storage: Storage) { }

 async Toggle1() {
     if(this.Ativar == true){
       this.storage.set('ativar', true);
     }
     if(this.Ativar == false){
       this.storage.set('ativar', false);
     }
     this.storage.get('ativar').then((data) => {
       this.Ativar = data;
   });
   };

I use the app emulator to run the app on my phone:

ionic cordova run android

When I make changes to Toggle and close the app, when I open it, the changes are not saved. I’ve been stuck a long time at this stage. Can anyone help me? I’m lost

1 answer

0

Friend you are setting the values in Storage, but when opening the application you need to do the get to get the saved result, in case when starting the app.

I saw that you did get in the Toggle1 method, but you should not call this method when starting the app, do separate this get and put it in an Oninit.

  • I did it, but it didn’t work. Can you help me? ngOnInit() {&#xA; this.storage.get('Ativar').then((data) => {&#xA; this.Ativar = data;&#xA; }); &#xA; this.storage.get('Ativar2').then((data) => {&#xA; this.Ativar2 = data;&#xA; }); &#xA; this.storage.get('Ativar3').then((data) => {&#xA; this.Ativar3 = data;&#xA; }); &#xA; this.storage.get('Ativar4').then((data) => {&#xA; this.Ativar4 = data;&#xA; }); &#xA;&#xA; };

Browser other questions tagged

You are not signed in. Login or sign up in order to post.