Не могу отобразить глобальную переменную в веб-интерфейсе .html - PullRequest
1 голос
/ 20 июня 2019

есть некоторые проблемы с моими переменными и не понимаю, почему.Я пытаюсь получить доступ к глобальной переменной, но не могу отобразить ее значение?

Это из-за асинхронного потока?

public cityName: string = "";


if (this.platform.is('cordova')) {
      this.geolocation.getCurrentPosition().then((resp) => {
        this.nativeGeocoder.reverseGeocode(resp.coords.latitude, resp.coords.longitude, this.nativeoptions)
        .then((result: NativeGeocoderResult[]) => console.log(result[0]))
        .catch((error: any) => console.log(error));
      });
    } else {
      this.cityName = "";
      navigator.geolocation.getCurrentPosition(function(location) {
        let latLng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
        googleMapsGeo.geocode({'location': latLng}, function(results, status) {
          if (status === 'OK') {
            if (results[0]) {
              this.cityName = results[0]['address_components'][2]['long_name'];
            } else {
              this.cityName = "";
              window.alert('No results found');
            }
          } else {
            this.cityName = "";
            window.alert('Geocoder failed due to: ' + status);
          }
        });
      });
    }

И home.page.html

<ion-header>
  <ion-toolbar color="primary">
      <div class="ion-text-center">
        <ion-title
        *ngFor=""
        >{{cityName}}</ion-title>
      </div>  
  </ion-toolbar>
</ion-header>

PS: console.log () возвращает правильное значение.

1 Ответ

1 голос
/ 21 июня 2019

Не уверен, что это ошибка копирования / вставки, но в вашем коде есть *ngFor="", которого не должно быть:

<ion-header>
  <ion-toolbar color="primary">
      <div class="ion-text-center">
        <ion-title
        *ngFor="" <---------------- here!
        >{{cityName}}</ion-title>
      </div>  
  </ion-toolbar>
</ion-header>

Кроме того, в вашем коде я заметил, что высначала используются функции со стрелками, но затем вы используете

// ...

navigator.geolocation.getCurrentPosition(function(location) { 
  // ...

  this.cityName = ...;
})

Выполнение function(location) {...} переопределяет то, что означает this, поэтому this.cityName больше не ссылается на свойство вашего компонента.Чтобы избежать этого, вам нужно использовать функции стрелок , вместо этого сделать что-то вроде (location) => { ... }.Я рекомендую прочитать документы , чтобы понять, как работают функции стрелок.

Поэтому при использовании функций стрелок ваш код будет выглядеть следующим образом:

if (this.platform.is('cordova')) {

  this.geolocation.getCurrentPosition().then((resp) => {
    this.nativeGeocoder.reverseGeocode(resp.coords.latitude, resp.coords.longitude, this.nativeoptions)
      .then((result: NativeGeocoderResult[]) => console.log(result[0]))
      .catch((error: any) => console.log(error));
  });

} else {

  this.cityName = "";

  navigator.geolocation.getCurrentPosition((location) => { // <---- here!
    let latLng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);

    googleMapsGeo.geocode({ 'location': latLng }, (results, status) => { // <---- and here!
      if (status === 'OK') {
        if (results[0]) {
          this.cityName = results[0]['address_components'][2]['long_name'];
        } else {
          this.cityName = "";
          window.alert('No results found');
        }
      } else {
        this.cityName = "";
        window.alert('Geocoder failed due to: ' + status);
      }
    });
  });
}
...