从存储中获取数据是异步的,这意味着我们的应用程序将在数据加载时继续运行。允诺让我们来执行一些动作,当数据加载完成后,无需暂停整个应用程序
所以这样一个例子应该是:
//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
更新离子2 RC
由于离子2 RC的发布一些变化了地点:
存储已从离子角度移除并置于单独的模块@ ionic/storage中。已经更新Starter以添加此内容,如果您使用的是存储系统,请确保将其添加到您的package.json中。在这里看到更多细节。
下面的例子演示了如何离子2储存:
首先我们编辑位于src/app/app.module.ts
的NgModule
。最重要的部分是添加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.set
和storage.get
方法:
this.storage.set('name', 'John').then(() => {
console.log('Name has been set');
});
this.storage.get('name').then((name) => {
console.log('Name: ' + name);
});
你试过了'this.storage.set('veeuID',11)); alert('Storage was set to:'+ JSON.stringify(this.storage.get('veeuID'))); ' – Akis
是的。看起来你不能只是调用.get你必须使用一个承诺。 –
是的,这里有一个很好的例子http://www.joshmorony.com/build-a-todo-app-from-scratch-with-ionic-2-video-tutorial/ – Akis