Javascript “无法访问”;这";内承诺

Javascript “无法访问”;这";内承诺,javascript,angular,this,Javascript,Angular,This,以下功能用于查找用户的国家/地区代码并将其存储在本地存储器中。但是,我无法在promise中访问此内容,控制台日志返回“null” 我正在调用NgOnInit中的findCountry函数 findCountry() { if (window.navigator.geolocation) { window.navigator.geolocation .getCurrentPosition(this.successfulLookup); } }

以下功能用于查找用户的国家/地区代码并将其存储在本地存储器中。但是,我无法在promise中访问此内容,控制台日志返回“null”

我正在调用NgOnInit中的findCountry函数

 findCountry() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation
        .getCurrentPosition(this.successfulLookup);
    }
  }
下面的问题已经被问了好几次,解决方法是使用Arrow函数,但我已经在使用Arrow函数了。感谢您的帮助

更新

  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");
      })  
  } 

尝试定义const self=this

您需要更改如下代码

window.navigator.geolocation
    .getCurrentPosition(this.successfulLookup.bind(this));
我们需要对successfulLookup方法使用bind(this),因为getCurrentPosition正在调用该方法。在这种情况下,这是指getCurrentPosition

我在youtube视频中发布了绑定的概念。如果您感兴趣,可以查看链接。我还发布了一个角度课程,其中有大约100个视频,涵盖了所有概念。这是下面的链接


在获取之前,尝试定义const self=this,然后在控制台日志中使用self。
.getCurrentPosition((位置)=>this.successfulLookup(位置))
。关于stackoverflow的问题很多this@PierreBurton它似乎不起作用
window.navigator.geolocation
    .getCurrentPosition(this.successfulLookup.bind(this));