在外部JavaScript库中定义函数时,如何检查未定义?(角度4/5) [英] How to check for undefined when function is defined in a external JavaScript libs? (Angular4/5)

查看:48
本文介绍了在外部JavaScript库中定义函数时,如何检查未定义?(角度4/5)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 4中,我正在使用Google Analytics(分析),并且遇到常见错误未定义ga".
此问题并非特定于Google Analytics(分析),第三方JavaScript库可以是所有内容,CanvasJS,PayPal ...

In Angular 4 I'm using Google Analytics and I have the common error "ga is not defined".
This problem is NOT specific for Google Analytics, the third party JavaScript lib can be everything, CanvasJS, PayPal ...

仅当我使用时间过早(例如ngInit)时才会引发该错误,当我在某个事件的函数上调用它时就可以了.

The error is thrown only when I use it too early (in the ngInit for example), it is fine when I call it on the function of some event.

HTML页面

<script>
    window.ga = window.ga || function () { (ga.q = ga.q || []).push(arguments) }; ga.l = +new Date;
    ga('create', 'UA-......', 'auto');
    ga('send', 'pageview', "home");
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>

我的组件.ts文件

declare let ga: Function

@Component({...})
export class HomePageComponent implements OnInit {

    ngOnInit() {
        ga("send", "event", ...)
    }
}

我尝试过:

  • ga&&ga("send","event",...)
  • if(ga!== undefined)ga("send","event",...)

浏览器中仍然有嘈杂的JavaScript错误.

I still have the noisy JavaScript error in the browser.

使用 try {ga("send","event",...)} catch(错误){} 我可以隐藏错误,但我希望进行适当的检查.
我也不想从JavaScrit负载中删除异步".

With try { ga("send", "event", ...) } catch (error) { } I can hide the error but I prefer a proper check.
I also don't want to remove the "async" from the JavaScrit load.

如何检查是否定义了 ga (或任何外部库)?

How can I check if ga (or whatever is the external lib) is defined ?

如@Hien Nguyen所建议:

As suggested by @Hien Nguyen:

// when called from ngInit "ga" is still not defined
if(typeof ga === "function") 
    ga('send', 'event', ...)

推荐答案

您可以检查 typeof ga ==='function'

@Component({...})
export class HomePageComponent implements OnInit {
  name = 'Angular';
  ga: Function;
  ngOnInit() {
    if (typeof this.ga === 'function') {
      this.ga("send", "event", "");
    }
  }
}

在控制台 https://stackblitz.com/edit/angular-6t8kza

这篇关于在外部JavaScript库中定义函数时,如何检查未定义?(角度4/5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆