0

My app stores data in a .ts file. A function allows to change a boolean value (displayed) in this file. Is there a way to save those changes in the file? I would like the values to be saved if the user close the app and re open it.

cards.ts

    export default
  {
    "cards": [
      {
        "id": "1",
        "question": "blabla",
        "answer": "blablabla",
        "hint": "blablablabla",
        "displayed": false,
...
      },
    ]
  };

cards.interface.ts

  export interface Card {
  id: string;
  question: string;
  answer: string;
  hint: string;
  displayed: boolean;
}

function that change the value

getRandom() {
    this.answerVisible = false;
    this.availableCards = this.cards.filter(card => !card.displayed);
    let rd = Math.floor(Math.random() * this.availableCards.length);
    this.randomCard = this.availableCards[rd];
    this.cards.find(card => card.id === this.randomCard.id).displayed = true;
  }
}
Ryley38
  • 99
  • 1
  • 3
  • 13

1 Answers1

0

Use localStorage in which the data is persisted until the user manually clears the browser cache or until your web app clears the data.
It's recommended you to use Ionic Storage when working with Ionic Application which uses SQLite When running in a native app context, and When running in the web or as a Progressive Web App, Storage will attempt to use IndexedDB, WebSQL, and local storage,

Usage:

npm install --save @ionic/storage

Register it in imports array of your root module

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    // ...
  ],
  providers: [
    // ...
  ]
})
export class AppModule {}

Finally, inject it into any of your components or pages:

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

export class MyApp {
  constructor(private storage: Storage) { }

  ...

  // set a key/value
  storage.set('name', 'Max');

  // Or to get a key/value pair
  storage.get('age').then((val) => {
    console.log('Your age is', val);
  });
}

PS:Refer the link for clear picture and usage

Vikas
  • 11,859
  • 7
  • 45
  • 69
  • Thanks for your help. I tried to use Ionic Storage following the instruction from the official documentation. It is set properly in app.modules.ts and my component but i have this error : **"Runtime error : storage is not define"**. In console : "Property "storage" is declared but never used". Any idea ? Also, I don't really understand how I can use storage based on my configuration. How can I save properties from this particular object ? – Ryley38 May 12 '18 at 20:22