2017-07-14 66 views
-1

你好,我想从诺言分配返回值到外部变量。 我尝试了很多次,但最后我放弃了。离子存储和变量

export class TestPage { 
    test:any; 

    constructor(private storage: Storage) { 

    storage.get('testy').then((value) => { 
     this.test = value; 
    }); 

    } 


    } 
+0

你怎么知道你失败了?你在哪里显示/使用'this.test'? – echonax

+0

它显示undefined,如果我把外面。然后 – Divers

+0

检查你试图存储值的地方 –

回答

0

与组件的属性,依赖注入的实例变量也应该使用this

this.storage.get('testy').then((value) => { 
      this.test = value; 
}); 
+0

仍然,结果是一样的:/ – Divers

+0

你打印的价值?你得到了什么?你不能在回调之外打印/访问它。你总是得到未定义的..因为它是一个异步调用。 –

+0

这就是问题,我需要从回调给外部变量的价值,所以我可以在其他地方使用。 – Divers

0

尽量给构造函数外的存储和查询

export class TestPage { 
test:any; 

constructor(private storage: Storage) {} 
this.storage.get('testy').then((value) => { 
    console.log('Testvalue is', value); 
    this.test = value; 
}); 


} 
0

尝试获得访问使用ionViewWillEnter事件加载页面之前的存储空间值:

export class TestPage { 
    test:any; 

    constructor(private storage: Storage) {} 
    ionViewWillEnter(){ 
     this.storage.get('testy').then((value) => { 
     console.log('Testvalue is', value); 
     this.test = value; 
     });   
    } 
} 
+0

仍然我得到未定义的错误:/ – Divers