在离子服务中不能从离子存储中获得价值

时间:2017-08-24 10:00:39

标签: angular ionic-framework ionic3 ionic-storage

我试图从离子存储中获取值,但我从函数中获得了价值。

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? 

2 个答案:

答案 0 :(得分:1)

这只是一个异步问题。

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /crm/api


RewriteRule ^getCustomers apihandler.php?action=getCustomers [NC,L,QSA]
RewriteRule ^getCustomer/(.*)$ apihandler.php?action=getCustomer&id=$1 [NC,L,QSA]
RewriteRule ^addCustomer/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+) apihandler.php?action=addCustomer&name=$1&surname=$2&address=$3&country=$4&email=$5&phone=$6 [NC,L,QSA]

只能在异步函数设置后使用xyz

您可以在完成异步功能时执行其余代码。或使用类似事件的东西来触发其他代码;

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

答案 1 :(得分: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.
});

我已将代码格式化为使用胖箭头功能,因为它使代码看起来更清晰。

如果您想访问相同的make一个组件级别变量并将其分配给响应并在模板中使用它

{{xyz}}

等模板中使用