[英]ngOninit variable is not binding in html angular 4
在谷歌地圖上工作,能夠顯示地圖,我想顯示當前位置,但不顯示
export class AppComponent {
title = '';
ngOnInit() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
console.log(p.coords.latitude);
console.log(p.coords.longitude);
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'latLng': LatLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
this.title = results[0].formatted_address;
console.log(this.title);
}
else {
console.log("Geocoding failed: " + status);
}
});
}
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
}
在這里“ this.title”,我正在獲取當前位置
HTML代碼
<h1> The Title is: {{title}}</h1>
在控制台中,我能夠看到標題值,為什么它沒有在html中綁定?
您正在使用在AppComponent
類的范圍內(在geocode
內的回調函數的范圍內)聲明的變量title
。 您必須使用其原始范圍訪問標題。
關鍵是要存儲this
到一個變量,在這種情況下是AppComponent的范圍
export class AppComponent {
title = '';
var self = this;
......
}
然后在任何回調函數中使用它。 在您的情況下,這是地址解析調用中的回調函數
geocoder.geocode({ 'latLng': LatLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
self.title = results[0].formatted_address; //Here we are using self, as the original context of title
console.log(this.title);
}
else {
console.log("Geocoding failed: " + status);
}
});
這里的另一個問題this-becomes-null也提供了答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.