0

This is likely a beginners question, but I'm having trouble using 'this' for global variables. I am using Ionic 4. And I'm trying to post a location to my database.

I have declared the following global variable in my class:

export class HomePage {

  myVar:any;

I can use it in a function like this:

  mainFunction(coordinates) {
    this.myVar = coordinates.coords.latitude;

The problem is that when i go one function deeper. The variable can not be accessed with 'this.'.

  mainFunction(coordinates) {
    navigator.geolocation.getCurrentPosition(this.helperFunction);
    console.log(this.myVar);

 helperFunction(coordinates) {
   this.myVar = coordinates.coords.latitude;

For some reason a nested function can not read or write the global variable. I get the following error:

ERROR TypeError: Cannot read property 'myVar' of null

How do I pass the value of myVar back to mainFunction? Thanks in advance.

I am calling the mainFunction with a button in a .html

 <ion-button expand="block" (click)="mainFunction()"></ion-button>
Dario
  • 71
  • 1
  • 5
  • 1
    How are you calling mainFunction? – evolutionxbox May 26 '20 at 09:01
  • I am calling the mainFunction with a button: – Dario May 26 '20 at 09:02
  • 1
    @evolutionxbox the problem is with `helperFunction` not `mainFunction`. Since the code is passing the direct reference to it, the context gets lost when invoked. – VLAZ May 26 '20 at 09:04
  • The way the geolocation API works is that it passes the coordinates to helperFunction. How can I pass the variable from that helperFunction to my mainFunction? – Dario May 26 '20 at 09:06
  • 1
    The helper function will be called *sometime later*. You cannot directly return anything to the main function. You could make a promise and await it. Or you just do the work that needs doing when the location becomes available inside the helper function. – deceze May 26 '20 at 09:16
  • Thanks. I solved it this by using `this.helperFunction.bind(this)` . – Dario May 26 '20 at 09:26

0 Answers0