2017-06-03 58 views
3

我正在使用iconic 2/angular 2并使用NativeStorage插件。Angular 2阅读本地存储的最佳地点

我有一个服务器URL,我让用户更改,它应该被保留。我对angular非常陌生,所以不确定应该怎么做才能调用NativeStorage.getItem。

显然,这应该是一个地方,这是非常首先,当用户启动应用程序的一切,由NativeStorage已初始化

是挂加载屏幕上的应用程序我当前的代码:

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) 
      ); 

     }); 
    }); 
    } 
} 

回答

1

我们从app.module.ts和配置仍然开始

@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(); 
     }); 
    } 
} 
+0

这个组件 – Vik

+0

@Vik我更新了我的代码,我认为我们可以先获取数据,然后检查平台/插件 –

1

你应该在你的组件中运行它。在this.platform.ready().then(() => {})的内部,放置您的本机存储代码。这可以确保cordova在您拨打电话时准备好处理原生插件。

如果您希望它立即加载本机存储数据,请将此代码写入constructor函数,ngOnInit或ionViewDidLoad中。

+0

嘛不清楚我应该在哪里在更新它@Vik – Vik

+0

写永久挂起我的代码 – wilsonhobbs