【问题标题】:angular can't call functions/variables inside a function角度不能在函数内调用函数/变量
【发布时间】:2021-06-28 08:30:32
【问题描述】:

我正在使用 google.maps.geocoder 在我的 Angular 应用中获取位置请求。在请求中,我提供了一个带有结果的回调函数。现在,如果我想调用在地图上显示标记的其他函数,代码会意外中断。我也无法设置在我的组件上定义的任何变量,当 Geocoder 回调函数中的代码发生时,看起来每个全局变量/函数都是未定义的。

如何解决此问题并从我的应用中的回调函数获取数据?

googleMapsFindLocation() {
        var address = this.locationName;

        this.geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == 'OK') {
                var mapCustomObj = new MapCustomObj();
                var marker = {
                    position: { lat: 46, lng: 16 },
                    info:
                        '<h2>' + "tekst" + '</h2></br>' +
                        '<p>' + "" + '</p>' +
                        '<p>' + "this.raceDto.seasonName" + '</p>' +
                        '<p>' + "this.raceDto.lat" + ' - ' + "this.raceDto.long" + '</p>'
                };
                mapCustomObj.marker = marker;

                //HERE IS THE PROBLEM. If i call showMap the code breaks, and the code in my showMap doesnt even get hit in debug
                this.showOnMap(mapCustomObj);

            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }

【问题讨论】:

    标签: angular typescript function google-maps


    【解决方案1】:

    将回调更改为箭头函数:从 function (results, status) { } 更改为 (results, status) =&gt; { } 。问题是何时调用回调 this 将是全局对象,而不是组件。但是箭头函数将this 绑定到它声明的当前上下文。

    提示:不要使用var 声明变量。首选const,其次是let

    提示2:由于对象{ 'address': address } 具有相同的键和变量命名,您可以将其传递为{ address }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 2017-05-17
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      相关资源
      最近更新 更多