Angular 2 best places to read your own storage

I am using iconic 2 / angular 2 and using the NativeStorage plugin.

I have a server url that I allow the user to modify and it should be saved. I'm very new to angular and so wasn't sure what should be the best place to call NativeStorage.getItem.

Obviously this should be the location that is the first when the user launches the entire application and that the NativeStorage is already initialized

my current code that hangs on the boot screen on boot:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { NativeStorage } from 'ionic-native';

import { HomePage } from '../pages/home/home';
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, storage: 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();
       platform.ready().then(() => {

          NativeStorage.getItem('CHAT_SERVER_HOST').then(
            (val) => { alert("init:" + val); },
            error => alert(error)
            );

      });
    });
  }
}

      

+3


source to share


2 answers


We start with app.module.ts and config

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

      



myapp.component.ts

export class MyApp {  

  constructor(platform: Platform, storage: Storage) {
     storage.get('your_item').then((val) => {
         console.log(val);
         this.platformReady();
     });

     platformReady() {
        // Call any initial plugins when ready
        this.platform.ready().then(() => {
           this.splashScreen.hide();
        });
     }
}

      

+1


source


You have to run it in your component. Inside, this.platform.ready().then(() => {})

enter your own storage code. This ensures that cordova is ready to handle native plugins when the call is made.



Write this code in a function constructor

, ngOnInit or ionViewDidLoad if you want to load your own store data instantly.

+1


source







All Articles