0

I have the following code to get the city from Ionic2 native AppPreferences:

import { AppPreferences } from '@ionic-native/app-preferences';

constructor(public appPreferences: AppPreferences) {
    
    console.log("The city is : " + this.loadPreferences("selectedCity"));
   
}

loadPreferences(preferenceKey: any){
    this.appPreferences.fetch(preferenceKey).then((res) => { return res; });
}

Inside .then((res) => {console.log}); the value is printed and works fine. But when I return the value or assign it to some variable then I get the value "The city is: undefined". Am I doing anything wrong?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Abdullah Feroz
  • 109
  • 2
  • 8
  • The fetch method is asynchronous and only runs way after the constructor is done. Can you give a code example to what fails? Is this the code you are trying to run? – misha130 Apr 11 '17 at 17:11
  • Yes this is the actual code which I am trying to run – Abdullah Feroz Apr 11 '17 at 17:19
  • Think about each line of code and WHEN it is executed – misha130 Apr 11 '17 at 17:49
  • I got it. As @misha130 said think about each line. The following line is printed before I get the result from async method: console.log("The city is : " + this.loadPreferences("selectedCity")); I changed my code a little bit. Now I run my code when I get the result in async function. Thanks alot – Abdullah Feroz Apr 11 '17 at 19:40
  • 1
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 Apr 11 '17 at 19:59

1 Answers1

1

I got it. As @misha130 said think about each line. The following line is printed before I get the result from async method:

console.log("The city is : " + this.loadPreferences("selectedCity"));

I changed my code a little bit. Now I run my code when I get the result in async function. Thanks a lot

Abdullah Feroz
  • 109
  • 2
  • 8