如何在typecipt的navigator.geolocation.getCurrentPosition的成功回调函数中传递额外的参数?

时间:2018-10-13 12:51:52

标签: typescript navigator

所以这件事困扰了我整整一天,我已经在网上搜索了数小时以寻求解决方案,但我找不到适合我的任何东西。

我发现大多数类似于以下代码,可以在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:无法读取null的属性“ ShowLocation”

我不知道如何使用打字稿进行这项工作。我不明白为什么会出现该错误。

编辑:在可能的重复链接中找到了解决方案,必须对“ this”使用bind,谢谢!


//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
          }

1 个答案:

答案 0 :(得分:0)

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

this.ShowLocation(position, this.map);

正确指向打字稿类的实例。您的代码应如下所示

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