[英]unable to get component variable value in angular 2 in frontend
Am unable to display mapLoc value in front end... any help? 无法在前端显示mapLoc值...有帮助吗?
Here is my component.ts file 这是我的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;
}
}
});
}
this is mycomponent.html file 这是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>
The value of this
can be different inside the callback (To check this, try console.log("this", this)
inside the callback.) . 值
this
可以在回调中不同的(要进行检查,尝试console.log("this", this)
回调里面)。 Try using a big arrow function instead to keep reference to your component. 尝试改用大箭头功能,以保持对组件的引用。
geocoder.geocode({ 'latLng': latlng }, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
this.mapLoc = results[1].formatted_address;
}
}
});
or cache a reference and use it in the old way: 或缓存引用并以旧方式使用它:
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;
}
}
});
That is very common issue of scoping : 这是范围界定的非常普遍的问题:
Just change : 只是改变 :
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
to 至
geocoder.geocode({ 'latLng': latlng }, (results, status) => {
OR 要么
geocoder.geocode({ 'latLng': latlng }, function (results, status) { ... }).bind(this)
For More Detail Ref : https://stackoverflow.com/a/47278161/2349407 有关更多详细信息,请参考: https : //stackoverflow.com/a/47278161/2349407
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.