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