简体   繁体   中英

Value not getting from ionic storage in ionic service

I am trying to get the value from ionic storage but I am getting value out of the function.

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? 

This is simply a asynchronous problem.

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

You can only use xyz after the asynchronous function set it

You can either do the rest of your code in the completion of your asynchronous function. or use something like an event to trigger other code;

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

I have formatted the code to use the fat arrow function as that makes the code look cleaner.

If you want to access the same make a component level variable and assign that to the response and use it in the template

Use in template like {{xyz}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM