【问题标题】:How to check for undefined when function is defined in a external JavaScript libs? (Angular4/5)在外部 JavaScript 库中定义函数时如何检查未定义? (Angular4/5)
【发布时间】:2019-09-22 16:45:26
【问题描述】:

在 Angular 4 中,我使用的是 Google Analytics,但出现常见错误“未定义 ga”。
这个问题不是谷歌分析特有的,第三方 JavaScript 库可以是一切,CanvasJS,PayPal ...

只有在我过早使用它时才会抛出错误(例如在ngInit中),当我在某些事件的函数上调用它时就可以了。

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 &amp;&amp; ga("send", "event", ...)
  • if(ga !== undefined) ga("send", "event", ...)

我仍然在浏览器中遇到嘈杂的 JavaScript 错误。

使用try { ga("send", "event", ...) } catch (error) { } 我可以隐藏错误,但我更喜欢适当的检查。
我也不想从 JavaScrit 加载中删除“异步”。

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


已解决

正如@Hien Nguyen 所建议的那样:

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

【问题讨论】:

标签: angular


【解决方案1】:

您可以查看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无异常演示

【讨论】:

    【解决方案2】:

    在您的 HTML 页面中先声明 analytics.js,然后再声明其余代码。

    <script async src='https://www.google-analytics.com/analytics.js'></script>
    <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>
    

    【讨论】:

    • 它加载了 async (我没有理由更改它)所以我认为它无法工作(我没有尝试过)。
    猜你喜欢
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多