angular - ionic 3 上的本地存储和选项卡菜单

标签 angular typescript local-storage ionic3

我在 tabs1 上有一张 map 。

我单击标记并发送本地存储标记标题并发送到 tab2。那工作很好。

that.passingData(dogwalkMarker.valueOf().parkid);

passingData(something: string) {
localStorage.setItem('passingData', JSON.stringify(something));
console.log(something);

但是当我第一次加载返回后的 tab2 时,出现了问题。在我加载应用程序上的任何页面并加载选项卡 2 后,它可以正常工作并返回良好!

我不明白我在哪里做错了。谢谢。

我在选项卡 2 上有以下代码。

scanOtopark() {
this.selectedOtopark = {};
let x = JSON.parse(localStorage.getItem('passingData'));

this.selectedOtopark = this.otoparks.find(otopark => otopark.parkqr === x);
if (this.selectedOtopark !== undefined) {
  this.otoparkFound = true;

  const toast = this.toastCtrl.create({
    message: "good",
    duration: 3000,
    position: 'top'
  });
  toast.present();
  console.log(this.selectedOtopark);
} else {
  this.otoparkFound = false;
  const toast = this.toastCtrl.create({
    message: 'something goes wrong',
    duration: 3000,
    position: 'top'
  });
  toast.present();
  this.selectedOtopark = {};
}

最佳答案

您的本地存储似乎存在异步问题。因此我强烈建议使用 native storage module 。由于它支持开箱即用的 Promise,因此您可以在异步情况下轻松使用它。如果您也安装 SQLite,它可以在所有平台上正常工作(尤其是 iOS 设备)需要。)

文档中的示例:

 // set a key/value
  storage.set('name', 'Max');

  // Or to get a key/value pair
  storage.get('age').then((val) => {
    console.log('Your age is', val);
  });

更新:

首次加载时,您需要使用:

 this.platform.ready().then(() => {

    });

更新2:

x: any;

scanOtopark() {
this.selectedOtopark = {};


this.platformCtrl.ready().then(() => {
  this.storageCtrl.get('passingData').then((data) => {
    this.x= data;

  this.selectedOtopark = this.otoparks.find(otopark => otopark.parkqr === this.x);
  if (this.selectedOtopark !== undefined) {
    this.otoparkFound = true;

    const toast = this.toastCtrl.create({
      message: "good",
      duration: 3000,
      position: 'top'
    });
    toast.present();
    console.log(this.selectedOtopark);
  } else {
    this.otoparkFound = false;
    const toast = this.toastCtrl.create({
      message: 'something goes wrong',
      duration: 3000,
      position: 'top'
    });
    toast.present();
    this.selectedOtopark = {};
  }
 });
});

关于angular - ionic 3 上的本地存储和选项卡菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761846/

相关文章:

angular - 为什么我可以通过修改从选择器接收的对象来修改状态?

javascript - 为什么以下函数抛出 Object is possible 'undefined' ?

angular - 如何使特定单元格在 primeNG 的内联可编辑行中不可编辑

javascript - 如何将项目添加到本地存储

angular - PrimeNG 按钮不在 angular2 中显示 fa 图标和标签

angular - 在 Angular 6 中禁用 mat-stepper 上已完成的步骤

javascript - *ngIf 上使用的 Angular 4 构造函数值

javascript - 使用js从本地存储中删除特定项目

javascript - 从本地存储中获取最后一个变量(按时间)

html - 如何使 ng2-charts 垂直条形图水平滚动?