[英]Angular how can I use embed script in Component
我正在嘗試在 Angular 中設置一種僅在流在線時顯示 Twitch 播放器的方式,因此在文檔中有這個內聯 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 中我們不能使用 < script > 標簽,而且我認為目前不可能使用 require 或 import 在我的組件 TypeScript 中使用它。
那么我將如何添加這個功能呢? 我知道在我可以實際引用該腳本標簽后該怎么做。
您可以動態創建腳本標簽,但我認為只需下載腳本並將其放在資產文件夾中,然后將腳本添加到angular.json
腳本列表中會更angular.json
或者您可以將腳本添加到index.html
head 部分
索引.html
<head>
<script src= "https://player.twitch.tv/js/embed/v1.js"></script>
...
</head>
將此添加到組件ngOninit
方法中
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>
您可能會發現另一種解決方案,例如 twitch 的 angular 包可以更清潔
更新
打字稿會出現類似[ts] Cannot find name 'Twitch'. [2304]
[ts] Cannot find name 'Twitch'. [2304]
一些庫有類型定義文件,但在我們的例子中,如果你只在這個文件中使用 Twitch 對象,你可以添加這個語句來告訴打字稿關於Twitch
對象
declare const Twitch: any;
如果您想在多個組件上使用 Twitch
src/global.d.ts
declare const Twitch: any;
最終推薦
安裝npm i twitch-js
並像這樣導入 Twitch 對象
import Twitch from 'twitch-js'
這將由 webpack 捆綁,因此您無需在 html 中添加任何腳本標記。
為此苦苦掙扎了一段時間。 我的腳本是異步的,最終我發現了postscribe 包。 像魔術一樣工作。
npm install --save postscribe
在代碼中:
import postscribe from 'postscribe'
//The script you want to load
const script = '<script src="https://darksky.net/map-embed/@radar,41.88,-87.62,10.js?embed=true&timeControl=false&fieldControl=false&defaultField=radar"></script>';
postscribe('#yourDivName', script);
v1.js
腳本src/twitch/
並將v1.js
腳本添加到其中"src/twitch/v1.js"
的scripts
數組中angular.json
src/twitch/
創建一個新文件twitch.d.ts
declare const Twitch: any;
twitch.d.ts
Twitch 庫現在可以在任何地方使用,而無需導入任何模塊,如下所示:
ngOnInit(): void {
new Twitch.Embed('containerId', {
channel: 'asmongold',
height: 500,
width: 400,
});
}
這就是我讓它工作的方式:
twitch.js
並粘貼所有內容。 ( src/assets/scripts/twitch.js
)。import Twitch from 'src/assets/scripts/twitch.js'
。您的組件應如下所示:
import { Component, OnInit } from '@angular/core';
import Twitch from 'src/assets/scripts/twitch.js';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
embedTwitch! : any;
constructor() { }
ngOnInit() {
this.embedTwitch = new Twitch.Embed("twitch-embed", {
width: 854,
height: 480,
channel: "monstercat"
});
}
}
<div id="twitch-embed"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.