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

时间:2017-08-02 18:22:40

标签: angular typescript typescript-typings youtube-javascript-api youtube-iframe-api

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

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

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

我也尝试在我的组件中使用/// <reference path,但这并没有帮助。在chrome / developer工具中,我收到错误。我能够ng buildng serve并且它可以成功构建/服务。

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"
  ]
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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