我正在使用 Angular 2 使用反向地理编码,它工作正常但我无法使用服务(setter 和 getter)设置值(即城市名称)
import { ShareService } from './services/ShareService';
class ConferenceApp {
constructor(public shareService: ShareService){
this.getGeoLocation();
}
public getGeoLocation(){
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(position=> {
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(this.lat, this.long);
let request = {
latLng: latlng
};
geocoder.geocode(request, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
let city = results[0].address_components[results[0].address_components.length-4].short_name;
this.shareService.setLocationDetails(city);
} else {
alert("No address available");
}
}
});
}, error => {
console.log(error);
}, options);
}
}
}
如果我尝试使用服务进行设置, this.shareService.setLocationDetails(城市); 我收到错误提示,
app.ts:303 Uncaught TypeError: Cannot read property 'shareService' of undefined
服务:
locationObj: any;
setLocationDetails(locationObj){
this.locationObj = locationObj;
}
getLocationDetails(){
return this.locationObj;
}
最佳答案
我觉得一切都很好。但是,我建议您使用 arrowfunction()=>
,如下所示,
// Removed function keyword and added arrow function
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
let city = results[0].address_components[results[0]
.address_components.length-4].short_name;
this.shareService.setLocationDetails(city);
} else {
alert("No address available");
}
}
});
关于angular - 使用 Angular 2 进行反向地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928472/