2017-11-14 17 views
0

フロントエンドでmapLocの値を表示できません...どのようなヘルプですか?ここでフロントエンドで角度2のコンポーネント変数の値を取得できません

は私component.tsが、これは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> 

答えて

0

thisの値はコールバック内部に異なる可能性がある

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; 
        } 
       } 
      }); 
} 

ファイルである(これを確認するには、内部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; 
       } 
      } 
     }); 
+0

ありがとうございました。それは働いた:) – Esco

0

スコープの非常に一般的な問題である:

だけ変更:

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

以上の詳細については参考

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

https://stackoverflow.com/a/47278161/2349407

+0

ありがとう。これはあまりにもうまくいった – Esco

+0

@エスコ、あなたは受け入れて答えをupvoteしますか? –

+0

私はすでにそれをやってみました。私のポイントは最低必要ポイントよりも低いので、私はupvoteできません。しかし、stackoverflowはそれが記録されると言います。 – Esco

関連する問題