【问题标题】:Invoking a JS function defined in Component Template from Angular2从 Angular2 调用组件模板中定义的 JS 函数
【发布时间】:2016-06-15 22:39:00
【问题描述】:

这是Angular2加载地图组件后需要调用的JS代码。代码在组件模板中定义。

<script>
   var x = document.getElementById("demo");
   function getLocation() {
       if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition(showPosition,showError);
       } else {
           x.innerHTML = "Geolocation is not supported by this browser.";
       }
   }

   function showPosition(position) {
       x.innerHTML = "Latitude: " + position.coords.latitude + 
       "<br>Longitude: " + position.coords.longitude; 
   }

   function showError(error) {
        switch(error.code) {
            case error.PERMISSION_DENIED:
                x.innerHTML = "User denied the request for Geolocation."
                break;
            case error.POSITION_UNAVAILABLE:
                x.innerHTML = "Location information is unavailable."
                break;
            case error.TIMEOUT:
                x.innerHTML = "The request to get user location timed out."
                break;
            case error.UNKNOWN_ERROR:
                x.innerHTML = "An unknown error occurred."
                break;          
        }   
    }
</script>

如何在onNgInit 方法中从组件调用getLocation() 函数? (或者如果可能的话,可以用更好的方式设计吗?)

接受答案和其他 SO 答案的最终解决方案:

Working Code In Plunker - integrating Geolocation, angular2-google-maps and Angular2 (RC1)

【问题讨论】:

  • 为什么不在 Angular 中移动代码?
  • 代码使用的是 HTML geolocation API...我看不出它如何在组件内移动...
  • 我看不出有什么问题;-)。你可以在 Angular 内部做所有你可以在外部做的事情。除了可能是时间问题,它必须在 Angular 完成加载之前完成。
  • 您的意思是我可以将getLocation 函数粘贴到组件类中并在生命周期挂钩上调用它?
  • 当然。使用 declare 告诉 TypeScript 编译器它应该假定名称存在(请参阅我更新的答案)。

标签: angular


【解决方案1】:

在脚本末尾添加

window.myGetLocation = getLocation;

在 Angular 组件中:

ngOnInit() {
  console.log(window.myGetLocation());
}

如果你添加

declare var navigator;

您可以在您的 Angular2 组件中使用 navigator.geolocation... 到您的打字稿脚本文件。

Plunker example

【讨论】:

    猜你喜欢
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多