I have problem to understand variabels in ionic or angular?

This is a very simple code that show the result of getiing the value from stored preferences. local store.

The problem is test is undefined seems it can not pas trough the test value out of the commando line?
What do i do wrong?

Why does it do like this.?? I am still in the same method.???
In my ts file can i not declare a variable in top and then use it in the method? or do i need to declare it over an over again?
Javascript was more easy than this.

getPrefs(prefs_language){
let test;
this.appPreferences.fetch(prefs_language).then((res) => {
test = res;
});

alert(test);

}

Other thing:
How does global variables work in ionic or angular?
Or are there no very easy example?

Put the alert(test) inside the promise response.

Yes i know that but why can not i use it outide the promise response? is it not the same method?
Should i not be able to use the app preferences inside the method?

Your problem isn’t the variable scope here. Is that your code alert(test) get’s executed before the promise is resolved.
You should research a bit and understand the basics of async operations in javascript. Do a google search a lot of resources in the wild :slight_smile:

This is exactly the same in JavaScript, so you can’t blame Ionic, Angular, or TypeScript. this.appPreferences.fetch is performing an asynchronous action, which is why it is returning a Promise. In the .then(), you have provided your handler for what is supposed to happen when .fetch() is done. Currently your handler looks like this:

(res) => {
    test = res;
}

This arrow syntax is the same as doing

function(res) {
    test = res;
}

But not really… Because the arrow syntax keeps the context of this, so you can continue to reference the current class inside of the function you provided in the .then(). What is happening, is that the alert() is called before the function you provided in the fetch() Promise, so test is still not defined. If you were to put your alert() inside a setTimeout (which I do NOT recommend, never, EVER!), you’ll see that it is probably working.

What you need to do, is to do whatever must happen when you get the result of fetch() inside the function you created ((res) => {...}).

You do seem to be a bit new to it all, so as @wingly recommended you should look up some stuff about sync/async and Promises

2 Likes

Your answer was great thanks.

The thing i want to accomplish is that i read the preferences from my stored local storage as the Ionic plugin appPreferences.

what i was trying to do to read the value and put it in a variable to test it.

But i can not figure out who to make a global variable i manage to fix it in javascript in my phonegap application before i changed to ionic and Angular.

Is it hare to make a global variable that lives through the application ??

I presured your answer because you explained it to me very well. thanks.

The first questions :::

can i not do anything like this?
variabel = appPreferences.store(prefs_language,prefs_value);
to save the value i have many settings that i need to read and put in variables …
Or if there is a global variables?

You should look in to using a service: https://angular.io/tutorial/toh-pt4. E.g. have one service for settings, users, backend, what not.

You could use async/await if you want to achieve what you’re looking for. Beware of catching errors though.

class SomeClass {
    fetch() {
        // This resembles the appPreferences.fetch method
        // Don't actually create this method, but use
        // this.appPreferences.fetch() instead of
        // this.fetch() in the method below
        return Promise.resolve("hi");
    }

    async getPrefs() {
        let prefs = await this.fetch();
        alert(prefs);
    }
}

Edit:
If the promise is rejected and not resolved, await someFunction() will throw an error. Wrap it in a try-catch. :slight_smile:

I missing some points on the last you maked for me. Only gettiing the key not the value.

I learn how to use services… so i useing an array in this example.

I have read the documentation about. https://ionicframework.com/docs/native/app-preferences/

App.preferences i getting success to store the data with this code. no problem at all. My problem is to read the values know. I can set the values with keys but not retrieve or read the values.


// Set the user preferences by id
// Example save the cityid and with the value ('cityid", 1)

setPrefs(typeid, value){
    if(typeid == 'cityid') this.appPreferences.store('cityid',value);
    if(typeid == 'langid') this.appPreferences.store('langid',value);
}

In my services i have this example…TWO ARRAYS

cityid = [ 'Lund', 'Västerås', 'Göteborg' ];
langid = [ 'Svenska', 'Engelska', 'Arabiska', 'Danska' ];

But when i want to get the values from with fetch command i very confused why are there no examples
you example i got to work but i don’t get the value i only getting the KEY for it… How do i get the value from it.
I missing the point of how to get the value.

Your exampel: Modified it but not getting the values… i missing something i dont understand.

class SomeClass {
    fetch(typeid) {
       // This resembles the appPreferences.fetch method
       // Don't actually create this method, but use
       // this.appPreferences.fetch() instead of
       // this.fetch() in the method below
       return Promise.resolve(typeid);
    }

    async getPrefs(typeid) {
        let prefs = await this.fetch(typeid);
        alert(prefs);
    }
}

This getPrefs code alert me the cityid and landid not the values …

I think you want ionic-storage instead. I also recommend not using async/await, as it makes for less readable code and encourages swallowing errors.

Thank you for the advice i change to ionic-storage and it working perfectly.

I have antoher issue.

If you load the prefspage i would like to set the values that is stored i picked up the stored values

But how do i set the selected items to right values. This is my code
The load function is ready but i need to tell each select box in my page to set to the right value on load.

In this method i getting right value from this onload method please give me an hint…

 ngOnInit() {
    this.storage.get('cityid').then((value) => { alert('vald stad = ' + this.dataService.cityid[Number(value)]); });
  }
  <ion-item>
    <ion-label>Stad</ion-label>
    <ion-select [(ngModel)]="cityid" (ionChange)="setPrefs('cityid',cityid)">
      <ion-option value="0">Flen</ion-option>
      <ion-option value="1">Halstahammar</ion-option>
      <ion-option value="2">Göteborg</ion-option>
      <ion-option value="3">Lund</ion-option>
      <ion-option value="4">Malmö</ion-option>
      <ion-option value="5">Stockholm</ion-option>
      <ion-option value="6">Uppsala</ion-option>
      <ion-option value="7">Västerås</ion-option>
      <ion-option value="8">Ă–rebro</ion-option>
    </ion-select>
  </ion-item>

You shouldn’t need the ionChange handler. Two-way binding should handle everything for you.

Have you an example?

  <ion-item>
    <ion-label>Stad</ion-label>
    <ion-select [(ngModel)]="cityid" (ionChange)="setPrefs('cityid',cityid)">
      <ion-option value="0">Flen</ion-option>
      <ion-option value="1">Halstahammar</ion-option>
      <ion-option value="2">Göteborg</ion-option>
      <ion-option value="3">Lund</ion-option>
      <ion-option value="4">Malmö</ion-option>
      <ion-option value="5">Stockholm</ion-option>
      <ion-option value="6">Uppsala</ion-option>
      <ion-option value="7">Västerås</ion-option>
      <ion-option value="8">Ă–rebro</ion-option>
    </ion-select>
  </ion-item>

This is my data.service.ts where i have the values

   cityid = [
        'Flen',
        'Halstahammar',
        'Göteborg',
        'Lund',
        'Malmö',
        'Stockholm',
        'Uppsala',
        'Västerås',
        'Ă–rebro'
    ];

Im using the ionChange to set and store the value with ionc-store. method.

Hi i have a question.

Suppose i have a variabel in my prefs.ts file and in my prefs file i have one variabel that I named to vPagename.
I declare it under export like this.

export class PrefsPage {
  vPagename: string = "";

And in my mehtods i set a value for my pagename but in my methods it does not understand my Vpagename varabiel declaration. Can i not pass out the value for my page from a function?

It seems little strange or i thinking wrong.

I need some more code to be able to understand what you mean :slight_smile:

declarde this on the top:

  export class HomePage {
menuCity: string = "";

…

this.service.menuCity is my menuCity variabel that i use in my html page as {{menuCity}}

Tryed this:

  ngOnInit() {
    this.storage.get('cityid').then((value) => { menuCity = this.service.cityid[Number(value)]; });
  }

My work araound

  ngOnInit() {
    this.storage.get('cityid').then((value) => { this.service.menuCity = this.service.cityid[Number(value)]; });
  }

I would like to use global or a variable in the file.ts method variable can not find any information on global variabel i found only services as deklared as this. : this.service.menuCity

but i found a workaround as a service.

Use global providers to store global states. Avoid constructions like static, etc., that can be used to kluge global Javascript variables. With a web app, you want each component to be as independent as possible, so pages can be created and destroyed whenever the local garbage collector wants to do it.

Please give me some examples
app.modules.ts file? or were i very new at angular and struggling to understand. the structure of it.
So please give me an example i will understand better.

Read official docs, or you will be banging your head against the wall for a long time. It is a losing strategy to trust randos on the internet.

1 Like