0

I'm using a geolocation provider i've made, where it is asychronous. It needs around 3-5 seconds to get the location of the user. I'm using a callback anonymous function and when i console.log everything works as expected and i read the value.

But when i try to set the value to the class variable by using THIS then says that THIS is undefined. Here is my code. locationTracker is a provider i've made.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SettingsPage } from '../settings/settings'
import { ListPage } from '../list/list'
import { Geolocation } from '@ionic-native/geolocation';
import {Observable} from 'rxjs/Rx';
import { LocationTrackerProvider } from '../../providers/location-tracker/location-tracker';

export class HelloIonicPage {
      public latitude:number = null;
      public longitude:number = null;

constructor(public navCtrl: NavController, public locationTracker: LocationTrackerProvider) {

    locationTracker.updateCoordinate(function (coords) {
        console.log(coords); // here it works perfectly
        this.latitude = coords.latitude; // TypeError: this is underfinded
        return coords;
    });

}

The question is how can i pass the value to latitude variable, as this is not recoginzed?

I do not plan to keep this inside the constructor, but for demonstrational reasons i have it there for the moment.

sebaferreras
  • 44,206
  • 11
  • 116
  • 134
Simos Fasouliotis
  • 1,383
  • 2
  • 16
  • 35

1 Answers1

0

I'm answering myself in case someone searches for the same - as exactly @yurzui said, changing main function to this works as expected:

locationTracker.updateCoordinate((coords) =>{
      this.latitude = coords.latitude;
      this.longitude = coords.longitude;
 });
Simos Fasouliotis
  • 1,383
  • 2
  • 16
  • 35