Search code examples
angulartypescriptionic2

Ionic2 AppPreferences undefined


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?


Solution

  • 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