在Angular 2中更新YouTube iFrame事件后的观看次数

时间:2016-11-19 18:56:57

标签: javascript angular youtube

我正在尝试在angular2中使用YouTube iFrame API,但我遇到了问题。

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>

当我点击“播放”时,视频会播放但“暂停”按钮不会显示(“播放”按钮也不会消失)。

当我再次点击 - 未隐藏 - “播放”按钮时,视频继续播放,“播放”按钮被“暂停”替换。所以它第二次工作。

我已经搜索了它,但没有找到解决方案:

1 个答案:

答案 0 :(得分: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 } });