В основном я нашел такие коды, как приведенный ниже, которые могут работать в javascript, но я не могу заставить его работать в Typescript.
//javascript version
navigator.geolocation.getCurrentPosition( function(position){
ShowLocation( position, variable );
});
function ShowLocation(position, variable){
console.log(position, variable);
}
//what I've tried on typescript
map:any="test";
private GetCurrentLocation(): void {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
/*something goes wrong here*/
this.ShowLocation(position, this.map);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
public ShowLocation(position: any, map: any): void {
console.log(position, map);
//do something with the position and map parameters
}
core.js: 1448 ОШИБКА TypeError: Невозможно прочитать свойство 'ShowLocation' со значением null
Я не знаю, как заставить это работать в машинописи.Я не понимаю, почему он выдает эту ошибку.
edit: нашел решение в возможной повторяющейся ссылке, пришлось использовать bind для «this», спасибо!
//working code
//what I've tried on typescript
map:any="test";
private GetCurrentLocation(): void {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
this.ShowLocation(position, this.map);
}.bind(this));
} else {
alert("Geolocation is not supported by this browser.");
}
}
public ShowLocation(position: any, map: any): void {
console.log(position, map);
//do something with the position and map parameters
}