首页 > 解决方案 > 无法在 Angular 中使用视频 url 动态更新 Vimeo 播放器

问题描述

使用 Vimeo SDK ( https://developer.vimeo.com/player/sdk/embed ) 我已将 Vimeo 播放器添加到我的 Angular (8) 组件中。视频 URL 通过来自我的父组件的 @Input() 进入。

它在初始加载时工作得很好。

当我在列表中选择另一个视频(这是一个单独的组件)时,它会@Input() videoUrl使用所选视频的更新 URL 来更新。

但是,尽管更新@Input() videoUrl正确,但我无法动态更新 Vimeo Player options.url

我尝试了两件事:

1/ 变化检测。我可以单击列表中的新视频,然后控制台注销新视频 URL @Input() 就好了。我使用此 URL 来更新我的 Vimeo 播放器options.url,但是 HTML 元素不会随新视频一起更新。

2/ 我也尝试将我的@Input() videoUrl 绑定到 div 元素,这同样不会更新播放器 url。

video.component.ts

import Player from '@vimeo/player';

@Input() videoUrl: string;

videoPlayer: Player;
options = {
  url: this.videoUrl,
  width: 800
};

ngAfterViewInit(): void {
  this.videoPlayer = new Player('vimeo-player', this.options);
}

ngOnChanges(changes: SimpleChanges): void {
  this.options.url = changes.videoUrl.currentValue;
}

video.component.html

<div id="vimeo-player"></div>

请注意,我也尝试过动态更新模板:

<div id="vimeo-player" [attr.data-vimeo-url]="videoUrl"></div>

我希望 Vimeo 播放器使用我提供的 @Input() 值动态更新其 videoUrl 选项

标签: angularvimeo

解决方案


Vimeo SDK 只是 JavaScript,而不是 Angular,因此它没有与 Angular 的更新周期挂钩。我想你需要调用vimeo play loadVideo 方法

像这样的东西

ngOnChanges(changes: SimpleChanges): void {

    // probably need to get the videoId from the url

    player.loadVideo(videoId).then(function(id) {
      // The new video is loaded
    }).catch(function(error) {
      switch (error.name) {
          case 'TypeError':
              // The ID isn't a number
              break;

          case 'PasswordError':
              // The video is password-protected
              break;

          case 'PrivacyError':
              // The video is private
              break;

          default:
              // Some other error occurred
              break;
      }
    });
}

推荐阅读