2017-08-24 73 views
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? 

回答

0

这只是一个异步问题。

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 
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. 
}); 

我已经格式化为使用FAT箭头的功能,使代码看起来更干净的代码。

如果要访问同一让组件级的变量并分配到响应,并用它在模板中的模板

使用像{{xyz}}