gpt4 book ai didi

javascript - ngOninit 变量在 html angular 4 中没有绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-04 15:53:46 25 4
gpt4 key购买 nike

在谷歌地图上工作,可以显示 map ,我想显示当前位置,但它不显示

     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 中没有绑定(bind)?

最佳答案

您正在使用 AppComponent 类范围内声明的变量 title,在 geocode 内的回调函数范围内。您必须使用其原始范围访问标题。

诀窍是将 this 存储到一个变量中,在本例中是 AppComponent 的范围

export class AppComponent {
title = '';
var self = this;
......
}

然后在任何回调函数中使用它。在您的例子中,它是 geocode 调用中的回调函数

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 中也提供了答案。

关于javascript - ngOninit 变量在 html angular 4 中没有绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47752644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com