2016-11-19 55 views
0

我試圖在angular2中使用YouTube iFrame API,但遇到問題。在Angular 2的YouTube iFrame事件後更新視圖

let onStateChange = (state) => { 
    if (state.data === window['YT'].PlayerState.PLAYING) { 
     console.log("window['YT'].PlayerState.PLAYING"); 
     this.isPlaying = true; 
    } 
    if (state.data === window['YT'].PlayerState.PAUSED) { 
     console.log("window['YT'].PlayerState.PAUSED"); 
     this.isPlaying = false; 
    } 
}; 

然後

this.player = new window['YT'].Player("video-player", {events: { onStateChange } }); 

回調處理播放器事件被執行,但意見沒有得到更新。

這裏是視圖:

<button class="control" (click)="play()" *ngIf="!isPlaying">Play</button> 
<button class="control" (click)="pause()" *ngIf="isPlaying">Pause</button> 

當我點擊「播放」,在視頻播放,但「暫停」按鈕不會顯示出來(「播放」按鈕不會消失要麼) 。

當我再次點擊 - 未隱藏 - 「播放」按鈕時,視頻繼續播放,「播放」按鈕被替換爲「暫停」。所以這是第二次。

我GOOGLE了它已經,但沒有找到一個解決方案:

回答

0

我只是找到了解決辦法。

進口NgZone

import { ..., NgZone } from '@angular/core'; 

添加NgZone作爲屬性

constructor(private ngZone: NgZone) {} 

然後

let onStateChange = (state) => { 
    this.ngZone.run(() => { // This was the trick 
     if (state.data === window['YT'].PlayerState.PLAYING) { 
      this.isPlaying = true; 
     } 
     if (state.data === window['YT'].PlayerState.PAUSED) { 
      this.isPlaying = false; 
     } 
    }); 
}; 

this.player = new window['YT'].Player("video-player", { events: { onStateChange } }); 
+0

你有一個鏈接到整個代碼?我正在努力獲得帶角度2運行的iframe api。 – Saerdn