I try to use the youtube iframe api for showing and controling video snippets with a smooth angular2 integration. And respecting the type concept of typescript is important to the webpack compiler and me :).
The quick setup of my tests:
use @angular/cli (Version 1.0.0-beta.32.3) to setup and install the ng2-youtube-player and then two small adjustments:
ng new test002
cd test002
npm install ng2-youtube-player --save-dev
The app.module was extended according to ng2-youtube-player, but in the app.component I had a small correction and an error:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',// app renamed to app-root
template: `
<youtube-player
[videoId]="id"
(ready)="savePlayer($event)"
(change)="onStateChange($event)"
></youtube-player>
`
})
export class AppComponent {
player: YT.Player;// Error: Cannot find namespace 'YT'
private id: string = 'qDuKsiwS5xw';
savePlayer (player) {
this.player = player;
console.log('player instance', player)
}
onStateChange(event){
console.log('player state', event.data);
}
}
For the error I faked the namespace with a youtube.d.ts file:
// dummy namespace...
export as namespace YT;
export interface Player {
name: string;
length: number;
extras?: string[];
}
Now using ng serve the webpack is compiling without error, even if there is YT unknown within the ng2-youtube-player package.
My question after intensive search on the internet: Can someone may provide a correct .d.ts file or tell me how to find out?
Actually,
ng2-youtube-player
provides its own TypeScript definitions, which is nice. You can see them undernode_modules/ng2-youtube-player/ng2-youtube-player.d.ts
.To use them, do something like this:
And in your component class (assuming of course you know how to use
Zone
):So the question made reference to
ng2-youtube-player
and I went looking for its TypeScript declarations. It was later clarified that the OP is really looking for ad.ts
file for the API itself.Using Yarn:
Or NPM:
The first line installs the API, the second installs the typings, which seem complete.
You import it using:
Usage as per the API. I tested this with VS Code and got very nice code insight when using this.
As @Myonara stated, the accepted answer involved importing a youtube upload library which is extraneous to the actual solution.
Better yet:
import 'youtube';
"typeRoots": [ "node_modules/@types" ], "types": [ "youtube" ]
The YT namespace will now be available.
I've been struggling with this and trying a bunch of things. In the end adding
youtube
to types in tsconfig.app.json which fixed it.The only other thing I did was:
This allows me to freely use
new YT.Player(...)
without any other tricks (such as just callingwindow['YT']
which I've seen.If anybody can offer an explanation as to how my IDE (VS Code) can find it but the compiler can't I'm still curious!.