Search code examples
ionic-frameworkionic3ionic-nativecordova-nativestorage

How save data permanently with Ionic 3?


I'm trying to make an introduction page that will read a QR Code, save the code and pass to another page. This will occur only the first time you open the application. When closing the app and reopen, the introduction page should not appear. So, what is my problem? I'm saving the code I read, but when I close the app and open again, the code that I had saved was lost and the introduction page appears. How do I solve this?

My IntroPage code is:

import { NativeStorage } from '@ionic-native/native-storage';
const STORAGE_KEY = 'hospitals';
...
scannedCode:string = null;

constructor(private navCtrl: NavController, 
            private barcodeScanner: BarcodeScanner, 
            private nativeStorage: NativeStorage,
            private toast: Toast) {}

public scanCode() {
  this.barcodeScanner.scan().then(barcodeData => {
    this.scannedCode = barcodeData.text;
    if (this.scannedCode === "123"){
      this.save(this.scannedCode);
      this.navCtrl.push(LoginPage);
    }
    else{
      this.makeToastMessage('Invalid Hospital!', '5000', 'bottom');
    }
  }, (err) => {
    console.log('Error: ', err);
  });
};

private save(val){
  console.log('data added ' + val);
  this.nativeStorage.setItem(STORAGE_KEY, {property: val})
    .then(
      () => console.log('Stored item!'),
      error => this.makeToastMessage('Error storing item', '5000', 'center')
    );
};

And my app.component.ts code is:

import { NativeStorage } from "@ionic-native/native-storage";
const STORAGE_KEY = 'hospitals';
...
rootPage:any;

constructor(platform: Platform, statusBar: StatusBar, 
            splashScreen: SplashScreen, public push: Push,
            public alertCtrl: AlertController, 
            private nativeStorage: NativeStorage) {
  platform.ready().then(() => {
    // Okay, so the platform is ready and our plugins are available.
    // Here you can do any higher level native things you might need.
    statusBar.styleDefault();
    splashScreen.hide();
    this.pushsetup();
    this.setRootPage();
  });
}

private setRootPage(){
  let localStorage:string = "Not got";
  this.nativeStorage.getItem(STORAGE_KEY)
    .then(
      item => localStorage = item.properity,
      error => console.log("Error getting item. Error: " + error)
    );
  alert(localStorage);

  switch (localStorage){
    case "123":
      this.rootPage = LoginPage;
      break;
    default:
      this.rootPage = IntroPage;
      break;
  }
}

Solution

  • It is not lost. You are checking the value outside your promise then function so it might be executed before data is fetched. You need to either use the switch case within then where you are looking for the data or chain the promises.

    private setRootPage(){
      let localStorage:string = "Not got";
      this.nativeStorage.getItem(STORAGE_KEY)
        .then(
            item => localStorage = item.properity,
            error => console.log("Error getting item. Error: " + error)
        ).then(_=>{
             switch (localStorage){
                case "123":
                    this.rootPage = LoginPage;
                    break;
                default:
                    this.rootPage = IntroPage;
                    break;
            }
        });
    }
    

    This will ensure you will check the value only after the value is fetched from the storage.

    Or in short:

     private setRootPage(){
          this.nativeStorage.getItem(STORAGE_KEY)
            .then(
                item => {
                    switch (item.property){
                    case "123":
                        this.rootPage = LoginPage;
                        break;
                    default:
                        this.rootPage = IntroPage;
                        break;
                    }
    
                },
                error => console.log("Error getting item. Error: " + error)
            )
    
    
    }