-1

Hello I want to assign returned value from promise to external variable. I tried many times but finally I give up.

  export class TestPage {
  test:any;

  constructor(private storage: Storage) {

    storage.get('testy').then((value) => {
        this.test = value;
    });

  }


  }
eko
  • 39,722
  • 10
  • 72
  • 98
Divers
  • 1
  • 1
  • 6

3 Answers3

0

Unlike component properties, instance variables of Dependency Injection should also be accessed using this

this.storage.get('testy').then((value) => {
            this.test = value;
 });
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • still, the result is the same :/ – Divers Jul 14 '17 at 12:17
  • Did you print value? What do you get? And you cannot print/access it outside then callback. You always get undefined.. since it is an asynchronous call. – Amit Chigadani Jul 14 '17 at 12:23
  • Thats the problem, I need to give value from callback to external variable so i can use in other place. – Divers Jul 14 '17 at 12:42
  • What external variable are you referring? `test` is it?. You are doing it right there, Assigning to global component variable is perfect. What is the problem? You can access it anywhere now. – Amit Chigadani Jul 14 '17 at 12:49
  • Yes to variable called test. Looks good, not working. In html page i tried to show it and then error, undefined – Divers Jul 14 '17 at 12:52
  • Ah! Your html is rendered before the component has loaded the data from storage.Give a condition before you use that in your template `
    {{test}}
    `
    – Amit Chigadani Jul 14 '17 at 12:55
  • Hmmm, now page loads, but my variable test is still empty, in .then statement it shows in console.log but outside it doesnt. – Divers Jul 14 '17 at 13:00
  • Strange! Show your template file please. – Amit Chigadani Jul 14 '17 at 13:34
0

Try to give the storage outside the constructor and check

export class TestPage {
test:any;

constructor(private storage: Storage) {}
this.storage.get('testy').then((value) => {
    console.log('Testvalue is', value);
    this.test = value;
});   


}
Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72
0

Try to get the value of storage before load page with ionViewWillEnter event:

export class TestPage {
   test:any;

   constructor(private storage: Storage) {}
   ionViewWillEnter(){
        this.storage.get('testy').then((value) => {
        console.log('Testvalue is', value);
        this.test = value;
      });          
   }
}
Carlos Franco
  • 210
  • 2
  • 9