Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在回调函数中访问数据_Javascript_Angular_Google Maps_Typescript_Google Geocoder - Fatal编程技术网

Javascript 在回调函数中访问数据

Javascript 在回调函数中访问数据,javascript,angular,google-maps,typescript,google-geocoder,Javascript,Angular,Google Maps,Typescript,Google Geocoder,我有一个对地址进行地理编码的函数,它返回同一地址的城市名称 // geocode the given address geocodeAddress(address, callback) { this.mapsAPILoader.load().then(() => { var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function

我有一个对地址进行地理编码的函数,它返回同一地址的城市名称

  // geocode the given address
  geocodeAddress(address, callback) {
    this.mapsAPILoader.load().then(() => {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          results[0].address_components.forEach(arrAddress => {
            if (arrAddress.types[0] == "locality") {
              callback(arrAddress.long_name);
            }
          })
        } else {
          console.log("Geocode was not successful for the following reason: " + status);
        }
      });
    });
  };
当我调用该函数并想要打印城市名称时,它会从geocodeAddress函数下面的代码行打印“未定义”,然后正确打印城市名称

this.geocodeAddress(this.offerAddress, data => {
  this.hostCity = data;
  console.log(this.hostCity);
});
console.log(this.hostCity);
我试图在second console.log函数之前添加一些超时,但没有成功

所以,我对从geocoder返回数据后如何访问该值感兴趣,因为我需要使用该数据存储在数据库中,如果我尝试这样存储的话

    this.geocodeAddress(this.offerAddress, data => {
            this.hostCity = data;
            this.service.addData({"address": this.offerAddress, "city": this.hostCity}, "/data")
                .subscribe(data => {
                  this.router.navigate(['list']);
                })
          });
它存储数据,但路由器。导航无法正常工作


所以我需要一个解决方案来访问geocodeAddress回调函数之外的hostCity,或者如何正确调用这个geocodeAddress回调函数中的另一个函数如果您使用的是TypeScript,您可以让您的
geocodeAddress
方法返回一个
Promise
,而不是使用回调,然后使用
async/await

async geocodeAddress(address): Promise<string[]> {
    return new Promise((resolve, reject) => {
        this.mapsAPILoader.load().then(() => {
           var geocoder = new google.maps.Geocoder();
           geocoder.geocode({ 'address': address }, function (results, status) {
               if (status == google.maps.GeocoderStatus.OK) {
                   const result: string[] = [];
                   results[0].address_components.forEach(arrAddress => {
                       if (arrAddress.types[0] == "locality") {
                           result.push(arrAddress.long_name);
                       }
                   });
                   resolve(results);
               } else {
                   console.log("Geocode was not successful for the following reason: " + status);
                   reject(status);
               }
           });
       });
    });
};

通过这种方式,您可以获得异步编程的好处,同时还可以获得同步编程的简单性。

您所说的“router.navigate无法正常工作”是什么意思?它将url导航到列表,但模板视图不是列表模板,它仍然在添加表单模板。我尝试调用另一个函数来打开错误对话框“this..confirmDialog(ErrorDialog,“Something error”);”。它会打开对话框,但没有消息,如果我在geocodeAddress回调函数之外调用此函数,那么除了处理
geocodeAddress
回调函数内的数据外,所有功能都会正常工作,请更改
函数(结果,状态){…}
以获得
(结果,状态)=>{…}
使用箭头函数保留
的值。为什么回答此问题而不是将OP指向cannonical异步参考问题?OP是否使用typescript并不重要。重要的是OP不太了解异步编程是如何工作的。这个解决方案帮助了我。非常感谢。
const data: string[] = await this.geocodeAddress(this.offerAddress);
this.hostCity = data[0];
// do whatever you want now