离子 2 本地存储无法按预期工作

ionic 2 local storage not working as expected

我无法让本地存储正常工作。当我这样做时:

this.VEEU_ID = 'veeuID';
this.storage.set(this.VEEU_ID, 11);
alert('Storage was set to: '+JSON.stringify(this.storage.get(this.VEEU_ID)));

我得到:

Storage was set to: {"_id":1733,"_state":1,"_result":"11","_subscribers":[]}

我认为 this.storage.get(this.VEEU_ID) 应该 return 值 11

Fetching data from Storage is asynchronous which means our application will continue to run while the data loads. A promise allows us to perform some action whenever that data has finished loading, without having to pause the whole application

所以一个例子应该是:

//set a value in storage
this.storage.set("age", 25);

//get the value from storage
this.storage.get("age").then((value) => {
   alert('Storage value: '+ value);
})

可以在 SqlStorage API page

上找到更多信息

Ionic 2 RC 更新

自从 Ionic 2 RC 发布以来,发生了一些变化:

Storage has been removed from ionic-angular and placed into a separate module, @ionic/storage. Starters have been updated to add this, make sure to add it to your package.json if you’re using the storage system. See more details here.

以下示例展示了如何使用 Ionic 2 存储:

首先我们编辑位于 src/app/app.module.tsNgModule。重要的部分是添加 Storage 作为提供者:

import { Storage } from '@ionic/storage';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    ...
  ],
  providers: [ Storage ] // Make sure you do that!
})
export class AppModule {}

现在我们可以将 Storage 注入到我们的组件中:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public storage: Storage) {

  }

}

将 Storage 注入组件后,我们可以使用 storage.setstorage.get 方法:

this.storage.set('name', 'John').then(() => {
  console.log('Name has been set');
});

this.storage.get('name').then((name) => {
  console.log('Name: ' + name);
});