Angular如何在组件中使用嵌入脚本 [英] Angular how can I use embed script in Component

查看:206
本文介绍了Angular如何在组件中使用嵌入脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Angular中设置一种仅在流在线时显示Twitch播放器的方式,因此在

I'm trying to set up in Angular a way of only showing Twitch player if the stream is online, so in the Documentation there is this inline HTML:

<script src= "https://player.twitch.tv/js/embed/v1.js"></script>
<div id="<player div ID>"></div>
<script type="text/javascript">
  var options = {
    width: <width>,
    height: <height>,
    channel: "<channel ID>",
    video: "<video ID>",
    collection: "<collection ID>",
  };
  var player = new Twitch.Player("<player div ID>", options);
  player.setVolume(0.5);
</script>

当然,尽管在Angular Components中我们不能使用<.脚本>标签,但我认为当前无法在我的组件TypeScript中使用require或import来使用它.

Of course though in Angular Components we can't use < script > tags and I don't think it's currently possible to use require or import to use this in my components TypeScript.

那么我将如何添加此功能?我可以实际引用该脚本标记后知道该怎么办.

So how would I go about adding this functionality? I understand what to do after I can actually reference that script tag.

推荐答案

您可以动态创建脚本标签,但我认为下载脚本并将其放入资源文件夹然后在angular.json

You can create a script tag dynamic but I think it's easier to just download the script and put it in assets folder and then add the script to script list in angular.json

或者您可以将脚本年龄添加到index.html头部

or you can add the script tage to index.html head section

index.html

index.html

<script src= "https://player.twitch.tv/js/embed/v1.js"></script>

将此添加到组件ngOninit方法

add this to component ngOninit method

  ngOnInit() {
    var options = {
        width: <width>,
        height: <height>,
        channel: "<channel ID>",
        video: "<video ID>",
        collection: "<collection ID>",
      };
      var player = new Twitch.Player("<player div ID>", options);
      player.setVolume(0.5);
   }

组件模板

<div id="<player div ID>"></div>

您可能会发现另一种解决方案,例如用于抽动的角度包可能更干净

You may find another solution like angular package for twitch can be more cleanr way

已更新

typescript会产生类似[ts] Cannot find name 'Twitch'. [2304]的错误,某些库具有类型定义文件,但在本例中,如果您仅在此文件中使用Twitch对象,则可以添加此语句以告知Typescript关于Twitch对象

typescript will give an error like [ts] Cannot find name 'Twitch'. [2304] some library has type definition files but in our case if you use Twitch object in this file only you can add this statement to tell typescript about the Twitch object

declare const Twitch: any;

如果要在多个组件上使用Twitch

if you want to use Twitch on multiple components

src/global.d.ts

src/global.d.ts

 declare const Twitch: any;

最终推荐

安装npm i twitch-js并像这样导入Twitch对象

install npm i twitch-js and import Twitch object like this

import Twitch from 'twitch-js'

这将由webpack捆绑在一起,因此您无需在html中添加任何脚本标签

this will bundled by webpack so you don't need to add any script tag in the html

twitch-devs

这篇关于Angular如何在组件中使用嵌入脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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