【问题标题】:Value not getting from ionic storage in ionic service没有从离子服务中的离子存储中获得价值
【发布时间】:2018-02-02 03:52:13
【问题描述】:
我试图从离子存储中获取价值,但我正在从函数中获取价值。
let xyz = '';
this.storage.get('user').then(function (response) {
xyz = response.accessToken;
console.log('in',xyz );
});
console.log('out', xyz);
//I am getting the value in the console in but not getting the console out.
//I want to use that token out side of this function.How can I get this token from storage?
【问题讨论】:
标签:
angular
ionic-framework
ionic3
ionic-storage
【解决方案1】:
xyz : string; // component level variable
this.storage.get('user').then((response) => {
this.xyz = response.accessToken;
console.log('in',this.xyz ); // this value is comming from a promise which takes times as it async function.
});
我已将代码格式化为使用粗箭头函数,因为这使代码看起来更清晰。
如果您想访问相同的组件级别变量并将其分配给响应并在模板中使用它
在模板中使用,如{{xyz}}
【解决方案2】:
这只是一个异步问题。
let xyz = '';
this.storage.get('user').then(function (response) {
xyz = response.accessToken;
console.log('in',xyz ); // <-- value is set here later than below
});
console.log('out', xyz); //<-- xyz is still '' here
异步函数设置后才能使用xyz
您可以在完成异步函数时执行其余代码。或者使用事件之类的东西来触发其他代码;
let subject = new Subject(); //global variable
this.storage.get('user').then(res => {
xyz = res.accessToken;
this.subject.next(xyz);
});
this.subject.subscribe(data => console.log(data)); //somewhere