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?

Thanks and regards in advance.

Two things: one that would have helped you understand the other one.

  • Always type the return value of your functions and don’t use any unless absolutely positively necessary, and preferenceKey could be typed as string.

  • If you had done that, you probably would have declared loadPreferences() as returning AppPreferences. It isn’t. It’s not returning anything at the moment, but it isn’t ever going to return AppPreferences. This is the fundamental truth of asynchronous programming.

constructor(public appPreferences: AppPreferences) {
  this.loadPreferences("selectedCity").then((city) => {
    // only in here can we rely on the data
    console.log("city is " + city);
  });
}

loadPreferences(preferenceKey: string): Promise<AppPreferences> {
  return this.appPreferences.fetch(preferenceKey);
}
1 Like