在 Angular 2 组件中导入命名空间给我一个构造函数错误

Importing a namespace in Angular 2 component gives me an constructor error

在 Angular 2 组件中导入命名空间给我一个构造函数错误

ERROR Error: Uncaught (in promise): TypeError: YT.Player is not a constructor
TypeError: YT.Player is not a constructor

这是我的 Angular 组件定义,它引用了这个命名空间

我也曾尝试在我的组件中使用 /// <reference path 但这没有帮助。在 chrome/developer 工具中我得到了错误。我能够做到 ng buildng serve 并且 builds/serves 成功。

import {
  Component,
  OnInit
} from '@angular/core';

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.css']

})

export class VideoComponent implements OnInit {

  private id: string = 'qDuKsiwS5xw';
  p: YT.Player;
  done = false;


  constructor() {

    this.p = new YT.Player('player', {
        height: 390,
        width: 640,
        videoId: 'M7lc1UVf-VE',
        events: {
            'onReady': this.onPlayerReady,
            'onStateChange': this.onStateChange
        }
    });
  }

  ngOnInit() {

  }

  onStateChange(event) {
    console.log('player state', event.data);
  }
  // 4. The API will call this function when the video player is ready.
  onPlayerReady(event) {
    event.target.playVideo();
  }
  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !this.done) {
      setTimeout(this.stopVideo, 6000);
      this.done = true;
    }
  }

  stopVideo() {
    this.p.stopVideo();
  }

}

这是我的 tsconfig.app.json 文件,我使用 DefinitelyTyped

http://definitelytyped.org/docs/youtube--youtube/classes/yt.player.html

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": ["youtube"]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

您必须使用 ng2 youtube 播放器: https://www.npmjs.com/package/ng2-youtube-player

只需在 index.html 的#script# 标签中导入外部库即可解决您的问题。