passing on value from geolocation to local method fails

I would like to get the user's current location and send it to a webservice, to get the current weather for that location.

I'm injecting my service in the constructor of my Component.

  constructor(private owmService: OwmService) {
  }

Get the location:

  ngOnInit() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        console.log("getCurrentPosition succesful", position); //I see the value of position, it's fine.
        this.getCurrentWeatherViaPosition(position); //this fails to pass on the value :(
      });
    }
  }

Error message: ERROR TypeError: Cannot read property 'getCurrentWeatherViaPosition' of null

I want to pass on the position to this method:

 getCurrentWeatherViaPosition(position: Position): void {
    this.owmService.getCurrentWeatherViaPosition(position)
      .subscribe((currentWeather: CurrentWeather) => {
        //got response from API
      });
  }

What am I doing wrong? How I'm supposed to pass on the value from the (async?) geolocation call to my local private method?

1 answer

  • answered 2017-11-12 20:56 Günter Zöchbauer

    If you use

    function () {...}
    

    this will point to geoLocation.

    Use arrow functions instead

     navigator.geolocation.getCurrentPosition((position) => {
    

    then this will point to the class instance where this code is.