【问题标题】:How to pass extra arguments in success callback function of navigator.geolocation.getCurrentPosition in typescript?如何在打字稿中 navigator.geolocation.getCurrentPosition 的成功回调函数中传递额外的参数?
【发布时间】:2019-03-18 11:43:27
【问题描述】:

我发现大多数类似下面的代码,它们可能在 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 ERROR TypeError: Cannot read property 'ShowLocation' of null

我不知道如何在打字稿中完成这项工作。我不明白为什么会出现这个错误。

编辑:在可能的重复链接中找到了解决方案,必须对“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
  }

【问题讨论】:

标签: typescript navigator


【解决方案1】:

您需要使用箭头函数而不是使用匿名函数作为navigator.geolocation.getCurrentPosition 方法的参数。箭头函数不会创建它自己的范围并使用父范围。因此,当您在此行中使用箭头功能时,您的 this

this.ShowLocation(position, this.map);

正确指向 typescript 类的实例。您的代码应如下所示 -

public GetCurrentLocation(): void {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition((position)  =>            { 
             this.ShowLocation(position, this.map);
          });
        } else {
          alert("Geolocation is not supported by this browser.");
        }
      }

      private ShowLocation(position: any, map: any): void {
        console.log(position.coords.latitude);
      }

如果您正在寻找 Angular 的示例,那么这里有一个演示

https://stackblitz.com/edit/angular-google-map-vcmrfe

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 2011-09-02
    • 2023-02-09
    • 2017-04-09
    • 2021-11-30
    相关资源
    最近更新 更多