如何将来自 geocoder.geocode() 的地址存储在 GeocoderService 中并将其 return 存储到 app.component?

How to store address from geocoder.geocode() in GeocoderService and return it to app.component?

我是 angular 和 TypeScript 的新手,我正在开发使用 google 映射查找地址的应用程序,但我无法存储来自 geocoder.geocode() 的地址.

我从这里尝试了解决方案:How do I return a variable from Google Maps JavaScript geocoder callback?

没关系,alert() 正在工作,但我想做的是将地址从 GeocoderService 传递到父组件并将其存储在那里。我试图将其存储在服务本身中,但我做不到!

地理编码器服务:

initialize() {
    this.geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    this.codeLatLng(function(addr){
      this.loc = addr; // <= here i can't store address it is undefined
      alert(addr);
      return this.loc;
    });

  }

  codeLatLng(callback) {
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    if (this.geocoder) {
      this.geocoder.geocode({'location': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            callback(results[1].formatted_address);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

app.component:

 constructor( private geolocationService: GeolocationService,
    private geocoderService: GeocoderService){
    this.position = {latitude: 0, longitude: 0}
    this.LatLng = new google.maps.LatLng( this.position.latitude, this.position.longitude);
  }

findMe(){
    this.geolocationService.getPosition().then((position: any) => {
      this.position = {latitude:position.coords.latitude,longitude: position.coords.longitude}
      this.LatLng = new google.maps.LatLng( this.position.latitude, this.position.longitude);
      this.map.setCenter(this.LatLng);
      this.loc = this.geocoderService.initialize(); //<= here i need this address to be returned and stored
      console.log(this.loc) // <= undefined
    })
 }

app.component.html:

<div #map style= "width:100%;height:400px"></div>
<button (click) = "findMe()">Find me</button>

如果问题很愚蠢,请帮忙,抱歉

1)

   function(addr){
          this.loc = addr; // <= here i can't store address it is undefined
          alert(addr);
          return this.loc;
        }

这个函数是一个回调函数,所以你不能 return 来自回调函数的数据你有未定义的 loc 变量的原因是因为 "This" 的应用程序组件 class 已经被函数的 "This" 遮蔽,因此要解决此问题,您必须使用箭头函数 (但它不能解决您的问题)

this.codeLatLng(addr=> this.loc = addr);

2)

  this.loc = this.geocoderService.initialize(); 

你永远不会得到一个值,因为初始化不会return一个值

3) 那么你需要做什么

由于 codeLatLng 的结果是异步的,请尝试使用 Subject 或 Observable 对象,并在应用程序组件中订阅该对象