【问题标题】:unable to get component variable value in angular 2 in frontend无法在前端的角度 2 中获取组件变量值
【发布时间】:2017-11-14 08:59:14
【问题描述】:

无法在前端显示 mapLoc 值...有什么帮助吗?

这是我的 component.ts 文件

export class mycomponent{

 mapLoc:any;

 constructor(){...}

openImageModal(lat,lng){
 this.mapLoc = '';
 var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        console.log(results[1].formatted_address); //able to console
                        this.mapLoc = results[1].formatted_address;
                    }
                }
            });
}

这是 mycomponent.html 文件

<ngui-map zoom="{{zoom}}" center="{{lat}}, {{lng}}" (mapReady$)="onMapReady($event,lat,lng)" (mapClick)="onMapClick($event)" (idle)="onIdle($event)">
                <marker *ngFor="let pos of position" [position]="[pos.lat, pos.lng]" draggable="true" (initialized$)="onMarkerInit($event)"></marker>
                    <info-window id="iw">
                        <div *ngIf="marker.display">
                        {{mapLoc}}
                        </div>
                    </info-window>
            </ngui-map>

【问题讨论】:

    标签: javascript angular google-maps reverse-geocoding


    【解决方案1】:

    this 的值在回调中可以不同(要检查这一点,请在回调中尝试console.log("this", this)。)。尝试使用big arrow function 来保持对您的组件的引用。

        geocoder.geocode({ 'latLng': latlng }, (results, status) => {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        this.mapLoc = results[1].formatted_address;
                    }
                }
            });
    

    或缓存引用并以旧方式使用它:

        let component = this;
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        console.log(results[1].formatted_address); //able to console
                        component.mapLoc = results[1].formatted_address;
                    }
                }
            });
    

    【讨论】:

      【解决方案2】:

      这是一个非常常见的范围问题:

      只是改变:

      geocoder.geocode({ 'latLng': latlng }, function (results, status) {
      

      geocoder.geocode({ 'latLng': latlng }, (results, status) => {
      

      geocoder.geocode({ 'latLng': latlng }, function (results, status) { ... }).bind(this)
      

      更多详情请参考:https://stackoverflow.com/a/47278161/2349407

      【讨论】:

      • @Esco,请您接受并投票赞成答案吗?
      • 我已经尝试过这样做。我不能投票,因为我的分数低于最低要求的分数。但是,stackoverflow 说它会被记录下来。
      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 2016-04-27
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2017-10-15
      相关资源
      最近更新 更多