angular - 使用 Angular 2 进行反向地理编码

标签 angular

我正在使用 Angular 2 使用反向地理编码,它工作正常但我无法使用服务(setter 和 getter)设置值(即城市名称)

import { ShareService } from './services/ShareService';
class ConferenceApp {
   constructor(public shareService: ShareService){
     this.getGeoLocation();

   }
    public getGeoLocation(){
          if (navigator.geolocation) {
              var options = {
                enableHighAccuracy: true
              };

              navigator.geolocation.getCurrentPosition(position=> {
                this.lat = position.coords.latitude;
                this.long = position.coords.longitude;
                let geocoder = new google.maps.Geocoder();
                let latlng = new google.maps.LatLng(this.lat, this.long);
                let request = {
                  latLng: latlng
                };   

                  geocoder.geocode(request, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                      if (results[0] != null) {
                       let city = results[0].address_components[results[0].address_components.length-4].short_name;                      

                       this.shareService.setLocationDetails(city);


                      } else {
                        alert("No address available");
                      }
                    }
                  });

              }, error => {
                console.log(error);
              }, options);
          }
        }
}

如果我尝试使用服务进行设置, this.shareService.setLocationDetails(城市); 我收到错误提示,

app.ts:303 Uncaught TypeError: Cannot read property 'shareService' of undefined

服务:

locationObj: any;
setLocationDetails(locationObj){
      this.locationObj = locationObj;
    }
    getLocationDetails(){
      return this.locationObj;
    }

最佳答案

我觉得一切都很好。但是,我建议您使用 arrowfunction()=>,如下所示,

// Removed function keyword and added arrow function
geocoder.geocode(request, (results, status) => {
  if (status == google.maps.GeocoderStatus.OK) {
    if (results[0] != null) {
      let city = results[0].address_components[results[0]
                .address_components.length-4].short_name;
      this.shareService.setLocationDetails(city);
    } else {
      alert("No address available");
    }
  }
});

关于angular - 使用 Angular 2 进行反向地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928472/

相关文章:

json - 如何在 Angular 7 的 Json 序列化中添加类型信息

twitter-bootstrap-3 - Angular 2解析模板错误

angular - Chart.js 类型错误 : item is null

javascript - Angular 2 Material Autocomplete - 获取(有效)所选项目

angular - 无法识别子模块 Angular 2 中的 Material 导入

angular - 根据用户选择顺序保存多个选择的 ngModel 绑定(bind)值

javascript - 如何有条件地将行添加到 Angular 5的表中

image - 如何在 Angular 4 中使用 ngStyle 作为背景 url

javascript - 为什么 Angular 6 出现图像未找到错误?

node.js - 在 Angular 中,使用 Renderer 相对于 ElementRef 有哪些优势?