【问题标题】:How to use function from cdn js script inside .ts file如何在.ts文件中使用cdn js脚本中的函数
【发布时间】:2019-07-09 09:47:20
【问题描述】:

我需要在 Angular 组件中使用远程 cdn 脚本。 (这是显示 GDPR 的弹出窗口)。我已经导入了脚本,但是我不能调用组件内部的方法。

所以我已经在我的 index.html 文件中导入了脚本。在我的 app.component.ts 文件中,我为要调用的函数声明了一个变量。但是浏览器仍然告诉我这个变量是未定义的。

Index.html 文件:

<!doctype html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
 <meta charset="utf-8">
  <title>AutoDiagnostic</title>
  <base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <script src="http://cdn.tagcommander.com/3905/uat/tc_autodiag_55.js"></script>
</body>
</html>

app.component.ts 文件:

import { Router, NavigationEnd, Event } from '@angular/router';
import { Component, OnInit } from '@angular/core';

declare let tc_events_55: any; // <=== the function i want to use

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private router: Router) {
    router.events.subscribe((event: Event) => {
      if (event instanceof NavigationEnd) {
        tc_events_55(this, 'virtualPageview', { page: this.router.url });
  }
});
 }
  ngOnInit(): void {}

  isTagCoCookieCreated() {
    return document.cookie.indexOf('TC_OPTOUT') !== -1;
  }
}

我希望它能让我能够使用 cdn .js 脚本中的函数,但我没有。我无法将脚本集成为本地资源,因为我必须根据部署环境从 cdn 调用它。

有什么想法吗? :)

【问题讨论】:

标签: angular


【解决方案1】:

通常情况下它不起作用。问题是您需要在您的app.module 中导入library。你需要在app.module中做这样的事情:

import 'tc_autodiag_55';

然后您就可以在其他组件中使用该库了。

【讨论】:

    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多