2017-06-09 34 views
2

我正在使用video.js來處理我的angular2視頻,但無法使其工作。 我在我的索引文件中使用video.js CDN。在angular2上設置video.js

<link href="https://vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet"> 
<script src="https://vjs.zencdn.net/5.11/video.min.js"></script> 

我有一個模板文件

<video *ngIf="videoUrl" id="{{id}}" 
    class="video-js vjs-big-play-centered" 
    controls 
    preload="auto" 
> 
    <source src="{{listing.url}}" type="video/mp4"> 
</video> 

和組件用的Video.js代碼中ngAfterViewInit

export class ListingComponent implements AfterViewInit, OnInit, OnDestroy { 

id: string; 

    ngAfterViewInit() { 
    videojs(document.getElementById(this.id), {}, function() { 
     // Player (this) is initialized and ready. 

    }); 
    } 

} 

的問題是,它顯示錯誤:「無法找到名爲 'videojs' 「。那是在ngAfterViewInit

我也嘗試通過npm和import {videojs} from 'video.js安裝video.js,但那也不管用。

有人請幫我看看如何使video.js與angular2一起工作。在此先感謝

回答

2

首先你不是初始化videojs。所以它顯示的videojs未定義。

只是覺得這下面的代碼:

 declare var videojs : any; 

     export class ListingComponent implements AfterViewInit, OnInit, OnDestroy { 

      id: string;  
      private videoJSplayer: any; 

      constructor(){} 
       ngAfterViewInit(){ 
        this.videoJSplayer = videojs(document.getElementById('video_player_id'), {}, function() { 
          this.play(); 
         }); 
        } 

      ngOnDestroy() { 
      this.videoJSplayer.dispose(); 
      } 
    } 

HTML:

<video *ngIf="videoUrl" id="video_player_id" 
    class="video-js vjs-big-play-centered" 
    controls preload="auto" 
> 
    <source src="{{listing.url}}" type="video/mp4"> 
</video> 

檢查此鏈接:videojs plunkerplunker with answered

+0

是的,你是對的。也,你有什麼想法,爲什麼它顯示錯誤,當我刷新頁面?錯誤是:'TypeError:提供的元素或ID無效。 (videojs)' – surazzarus

+0

這意味着。你的ID不是唯一的,如果你不想改變ID。檢查更新後的答案 –

+0

我有每個視頻的動態和唯一的ID。 – surazzarus

0

你應該使用這個

@Component({ 
    encapsulation: ViewEncapsulation.None 
}) 
0

當角4+和角度CLI使用,我找到了最好的解決方案是通過NPM包安裝,然後添加到videojs中的腳本angular-cli.json,像這樣:

"scripts": [ 
    "../node_modules/video.js/dist/video.min.js" 
] 

從那裏,添加到您的typings.d.t.s

declare const videojs: any; 

然後初始化按正常:

ngAfterViewInit() { 
     this._videoPlayer = videojs(document.getElementById('video'), {},() => { 
     }); 
}