【问题标题】:Angular 2 best place to read native storageAngular 2 阅读本机存储的最佳位置
【发布时间】:2017-11-04 12:37:56
【问题描述】:

我正在使用标志性 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)
            );

      });
    });
  }
}

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    【讨论】:

    • 嗯还是不清楚应该在哪里写组件
    • 更新了@Vik
    【解决方案2】:

    我们从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 我更新了我的代码,我想我们可以先获取数据,然后检查平台/插件是否准备就绪
    猜你喜欢
    • 2018-02-28
    • 2020-08-22
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多