无法在前端.html中显示全局变量

时间:2019-06-20 20:22:44

标签: api ionic-framework maps

我的变量有一些问题,不明白为什么。我试图访问全局变量,但无法显示其值?

是因为异步线程吗?

main()

和home.page.html

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

PS:console.log()返回正确的值。

1 个答案:

答案 0 :(得分:1)

不确定是不是复制/粘贴错误,但是您的代码中有一个*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) => { ... }的操作。我建议阅读 the docs 以了解箭头功能的工作原理。

因此,使用箭头功能,您的代码将如下所示:

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