0

The following function is used to find the country-code of the user and store it in the local Storage. However, I am unable to access this inside the promise and the console log returns "null".

  successfulLookup(position) {
    const { latitude, longitude } = position.coords;
    fetch(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=d2c9d6477126472fbe51b721a2d34399`)
      .then((response) => { return response.json() })
      .then((jsonRes) => {
        console.log(jsonRes.results[0].components.country_code);   
        console.log(this); 
        this.dataSharingService.universalLocalStorageSetter(jsonRes.results[0].components.country_code,"countryCode");
      })  
  } 

I am calling the function findCountry inside NgOnInit

 findCountry() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation
        .getCurrentPosition(this.successfulLookup);
    }
  }

The following question has been asked a couple of times and the solution is to use Arrow function but I am already using an Arrow function. Any help is appreciated.

UPDATE

  successfulLookup(position) {
    const { latitude, longitude } = position.coords;
    const self = this;
    fetch(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=d2c9d6477126472fbe51b721a2d34399`)
      .then((response) => { return response.json() })
      .then((jsonRes) => {
        console.log(jsonRes.results[0].components.country_code);   
        console.log(self); 
        self.dataSharingService.universalLocalStorageSetter(jsonRes.results[0].components.country_code,"countryCode");
      })  
  } 

tried defining const self=this

1 Answers1

1

You need to change the code like

window.navigator.geolocation
    .getCurrentPosition(this.successfulLookup.bind(this));

We need to use bind(this) to the successfulLookup method because that method is calling by the getCurrentPosition. In that case, this refers to the getCurrentPosition.

I posted the concept of a bind in my youtube videos. If you are interested you can check the link. I also posted an angular course that has about 100 videos covering all the concepts. Here is the link below.

Leela Web Dev

Leela Narasimha
  • 130
  • 1
  • 5