【问题标题】:Angular 7: Use external script in componentAngular 7:在组件中使用外部脚本
【发布时间】:2019-03-28 08:35:54
【问题描述】:

我正在尝试使用 Twitch API 在我的网络应用中嵌入频道。

说明如下:

<html>
  <body>
    <!-- Add a placeholder for the Twitch embed -->
    <div id="twitch-embed"></div>

    <!-- Load the Twitch embed script -->
    <script src="https://embed.twitch.tv/embed/v1.js"></script>

    <!-- Create a Twitch.Embed object that will render within the "twitch-embed" root element. -->
    <script type="text/javascript">
      new Twitch.Embed("twitch-embed", {
        width: 854,
        height: 480,
        channel: "monstercat"
      });
    </script>
  </body>
</html>

我已将https://embed.twitch.tv/embed/v1.js 文件包含在我的assets 文件夹和angular.json 中。

    "scripts": [
      "src/assets/twitch/twitch-embed-v1.js"
    ]

我的组件文件如下所示:

import Twitch from '../../../../../assets/twitch/twitch-embed-v1';

export class TwitchPlayerComponent implements OnInit {

  ngOnInit() {
    const options = {
      width: 854,
      height: 480,
      channel: '424976424',
    };
    const player = new Twitch.Embed('twitch-embed', options);
    player.setVolume(0.5);
  }

}

该脚本出现在 Chrome devtools 的我的源面板中,但产生了以下错误:

Embed is not a constructor

正确使用脚本的障碍是什么?

【问题讨论】:

标签: angular typescript twitch


【解决方案1】:

twitch 的 v1 还没有 TypeScript 类型,这将在 v2 中出现。您不应该将脚本添加到您的资产文件夹中。如果 twitch 有更新怎么办?您必须手动更新资产文件夹。

无论如何,我认为,要使用 twitch SDK,您可以执行以下操作:

npm install twitch-js@next

在你的 TS 中:

import * as Twitch from 'twitch-js';

new Twitch.Embed({...});

【讨论】:

  • 你有工作的 stackblitz 或代码吗?这是我最初的方法,但会导致同样的错误。我认为将脚本带入内部会消除变量,而不是长期保持这种状态。
【解决方案2】:

我遇到了同样的问题,这就是为什么我决定为 Twitch 交互式嵌入播放器实现一个 Typescript 包装器。这与 Angular 100% 兼容,所以如果您仍然需要一种方法来实现这一点,请查看这个存储库。希望对你有帮助^^

https://github.com/frozencure/twitch-player

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多