0

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 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.