Ionic Storage / Toggle

I have a very simple question , i am building an app where i have a settings page with a toggle input for a user to turn on and off some alerts . My question is how do i save the toggle value so as when someone closes the app or navigate to another page the toggle status should not get lost and the current toggle should be reflected in html.

Page.html:

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

Ts:

export class Tab1Page {

  toggleStatus: any;

  

  constructor(public alert: AlertController, 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;
      })
    });
  }

  Button1() {
    console.log(`changing toggleStatus to '${this.toggleStatus}'`);
    this.storage.set('toggleStatus', this.toggleStatus);
  }

Get this error:
Property ‘ready’ does not exist on type 'Storage’

Can someone help me?

Ionic Storage 3.0 does not have ready anymore, so you may have resorted to a tutorial of a different version.

Storing the setting across sessions (so after app closure) - here you can use the local storage or push to a server. Whatever your use case is.

Using localstorage to persist data across pages is technically possible but undesirable. Here Angular has defined the concept of a service. Maybe best for you to check the tutorial on angular.io to learn the basic architectural elements.

Where soon after you find yourself figuring out how to deal with lifecycle of compont and updating data across your app. When you start meddling with lifecycle hooks for getting data, then it is time to learn about BehaviorSubject instead. And this forum has lots of info about this (read: people struggling with the acceptance of their async fate)

1 Like

In addition to @Tommertom’s typically excellent suggestions, I would also urge you not to store each of these booleans separately. Define a single Preferences interface containing all user preferences, read it from storage at app startup, write it back optimistically whenever there is a change. This will centralize and reduce the interaction with storage.