Angular 2最佳的本地存储读取位置

3

我正在使用iconic 2/angular 2,并使用NativeStorage插件。

我有一个服务器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)
            );

      });
    });
  }
}
2个回答

1

我们从 app.module.ts 和 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();
        });
     }
}

@Vik 我更新了我的代码,我认为我们可以先获取数据,然后检查平台/插件是否准备好。 - Thien Hoang

1
您应该在组件中运行它。在 this.platform.ready().then(() => {}) 中,放置您的本地存储代码。这可以确保 Cordova 准备好处理原生插件时,您可以进行调用。
如果您希望立即加载本地存储数据,请将此代码编写到 constructor 函数、ngOnInit 或 ionViewDidLoad 中。

仍然不清楚在组件中应该写入哪里。 - Vik
更新了@Vik - wilsonhobbs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接