Получил это ноль - PullRequest
       1

Получил это ноль

3 голосов
/ 03 марта 2020

У меня странная ошибка "это ноль". Я не знаю, в чем проблема. Это мое демо Stackblitz.com и пример кода для справки.

Компонент

ngOnInit() {
    this.getCurrentLocation();
  }

  getCurrentLocation() {
   navigator.geolocation.getCurrentPosition(position =>{
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.weatherInfo(this.lat, this.lng)
},function(){
       this.origin = { lat: '3.140853', lng: '2.693207'};
       console.log(this.origin)
       this.weatherInfo(this.origin.lat, this.origin.lng)
})



  }
  weatherInfo(lat, lng){
    console.log(lat, lng);
  }

Ответы [ 2 ]

5 голосов
/ 03 марта 2020

Вам необходимо использовать функцию стрелки (() => { вместо function() {) из-за требуемой области видимости:

getCurrentLocation() {
   navigator.geolocation.getCurrentPosition(position =>{
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.weatherInfo(this.lat, this.lng)
}, () => { // Here
       this.origin = { lat: '3.140853', lng: '2.693207'};
       console.log(this.origin)
       this.weatherInfo(this.origin.lat, this.origin.lng)
})

Возможно, стоит прочитать: Понимание "this" в javascript со стрелками или стрелками и ключевым словом this

2 голосов
/ 03 марта 2020

Вам необходимо либо связать это с анонимной функцией, либо написать в виде функции стрелки, чтобы ваша ссылка на нее оставалась.

Опция 1:

getCurrentLocation() {
// Your Method
}, this.logging().bind(this))

logging() {
// Do something
}

Опция 2:

getCurrentLocation() {
// Your Method
}, () => {// Do something})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...