2016-04-18 47 views
3

我无法使本地存储正常工作。当我这样做:离子2本地存储未按预期工作

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)应返回的值11

+0

你试过了'this.storage.set('veeuID',11)); alert('Storage was set to:'+ JSON.stringify(this.storage.get('veeuID'))); ' – Akis

+1

是的。看起来你不能只是调用.get你必须使用一个承诺。 –

+1

是的,这里有一个很好的例子http://www.joshmorony.com/build-a-todo-app-from-scratch-with-ionic-2-video-tutorial/ – Akis

回答

9

从存储中获取数据是异步的,这意味着我们的应用程序将在数据加载时继续运行。允诺让我们来执行一些动作,当数据加载完成后,无需暂停整个应用程序

所以这样一个例子应该是:

//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.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.setstorage.get方法:

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

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

和如何赋值给外部变量? –

+0

假设在样本类别中: 'public key:any = null; 公共存储:...; (this.key); //将显示该值(012) } console.log(this.key); //将显示null }' 为什么?我研究了承诺但我不明白为什么它不会初始化整个类中的公共变量? –