You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic 3如何永久保存数据?扫码引导页重复显示问题求助

解决引导页重复显示与扫码内容丢失的问题

嘿,我看到你遇到了两个核心问题,导致扫码内容重启后丢失、引导页重复显示,咱们一步步来修复:

问题1:异步操作的顺序错误

NativeStorage.getItem()是异步操作(返回Promise),但你当前的代码在Promise还没完成时就执行了switch判断,这时候localStorage还是初始值"Not got",所以每次都会跳转到IntroPage。

问题2:拼写错误

在app.component.ts的getItem回调里,你写的是item.properity,但保存时用的是property——这个拼写错误导致你根本读取不到之前保存的值。


修改后的app.component.ts代码

把页面跳转逻辑放到getItem的then回调里,确保等异步读取完成后再判断:

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(() => {
    statusBar.styleDefault();
    splashScreen.hide();
    this.pushsetup();
    this.setRootPage();
  });
}

private setRootPage(){
  this.nativeStorage.getItem(STORAGE_KEY)
    .then( item => {
      // 修正拼写错误:properity → property
      const storedValue = item.property;
      alert(storedValue);
      switch (storedValue){
        case "123":
          this.rootPage = LoginPage;
          break;
        default:
          this.rootPage = IntroPage;
          break;
      }
    }, error => {
      console.log("Error getting item. Error: " + error);
      // 读取失败(首次打开或存储异常),默认跳引导页
      this.rootPage = IntroPage;
    });
}

确认IntroPage的保存逻辑

你的IntroPage代码基本没问题,再确认下STORAGE_KEY和保存的键名一致:

// IntroPage里的save方法,确保键名正确
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') );
};

额外注意事项

  1. 确保NativeStorage插件已经正确安装并在app.module.ts中注册:
    // app.module.ts
    import { NativeStorage } from '@ionic-native/native-storage/ngx';
    
    @NgModule({
      ...
      providers: [
        ...
        NativeStorage,
        ...
      ]
    })
    
  2. 测试时可以先卸载旧应用再重新安装,避免之前的异常存储数据干扰。

这样修改后,首次扫码保存"123"后,下次重启应用就会直接跳转到登录页,不会再显示引导页了。

内容的提问来源于stack exchange,提问作者Kim Ruan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:36:53