0

我试图从离子存储中获取价值,但我正在从功能中获取价值。

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? 
4

2 回答 2

1

这只是一个异步问题。

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
于 2017-08-24T10:03:13.507 回答
0
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}}

于 2017-08-24T10:03:40.747 回答