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>
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.
Angular2 removes <script> tags automatically from templates to stop people using this functionality as a "poor's man" loader. The issue here is that script tags currently have more uses than just loading code or other script files.
To include a JavaScript library in your TypeScript application you must first include it in your HTML file as a script tag. To use the library you must add the following to one of your ts files: declare var libraryVar: any; Replace libraryVar with a variable, function, or class within your JavaScript library.
You can create a script tag dynamically, 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
or you can add the script to index.html
head section
index.html
<head>
<script src= "https://player.twitch.tv/js/embed/v1.js"></script>
...
</head>
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);
}
Component template
<div id="<player div ID>"></div>
You may find another solution like angular package for twitch can be more cleaner way
Updated
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;
if you want to use Twitch on multiple components
src/global.d.ts
declare const Twitch: any;
final recommendation
install npm i twitch-js
and import Twitch object like this
import Twitch from 'twitch-js'
this will be bundled by webpack, so you don't need to add any script tag in the html.
twitch-devs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With