我正在使用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(city); 我会收到错误提示,
app.ts:303 Uncaught TypeError: Cannot read property 'shareService' of undefined
这项服务:
locationObj: any;
setLocationDetails(locationObj){
this.locationObj = locationObj;
}
getLocationDetails(){
return this.locationObj;
}