绑定组件中发生的事件的最佳方法

时间:2019-05-30 11:51:05

标签: angular

Angular4应用: 我在组件Compa中使用了videogular2库(或者说elem),然后在CompB中使用CompA。

我需要订阅CompA中的videogular(或video elem)事件,以便如果发生播放/暂停,它将在ServiceX中发出或收听。

首先,我没有确切地解决问题的方法,其次,我想采用哪种最佳方法来实现这一目标?

1 个答案:

答案 0 :(得分:2)

根据videogular2 here的文档,您需要绑定到onPlayerReady组件上的vg-player事件。像这样:

<vg-player (onPlayerReady)="onPlayerReady($event)">
    <video [vgMedia]="media" #media id="singleVideo" preload="auto" controls>
        <source src="https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm">
    </video>
</vg-player>

然后您将在event事件处理程序中获得一个onPlayerReady。此事件基本上是公开getDefaultMedia().subscriptions的API。这样,您可以订阅Observableplay listed here之类的pause。像这样:

import { Component } from '@angular/core';
import { VgAPI } from 'videogular2/core';

import { PlayerStateService } from './player-state.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  api: VgAPI;

  constructor(private playerState: PlayerStateService) { }

  onPlayerReady(api: VgAPI) {
    console.log('playerReady');
    this.api = api;
    this.api.getDefaultMedia().subscriptions.play.subscribe(
        (event) => {
          this.playerState.updatePlayerState('play');
        }
    );

    this.api.getDefaultMedia().subscriptions.pause.subscribe(
        (event) => {
          this.playerState.updatePlayerState('pause');
        }
    );

  }
}

现在您已经知道播放器已暂停或恢复,您可以轻松创建带有BehaviorSubject的共享服务。每次播放器状态发生变化时,您都可以通过在其上调用BehaviorSubject方法在该next上设置一个新值。

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class PlayerStateService {

  private state: BehaviorSubject<string> = new BehaviorSubject<string>('');
  public state$: Observable<string> = this.state.asObservable();

  constructor() { }

  updatePlayerState(playerState: string) {
    this.state.next(playerState);
  }

}

然后您可以在其他组件中订阅该组件,并在其中收听播放器中的这些状态变化。

import { Component, Input } from '@angular/core';
import { Observable } from 'rxjs';

import { PlayerStateService } from './player-state.service';

@Component({
  selector: 'hello',
  template: `<h1>Current state of the player is {{ playerState$ | async }}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {

  playerState$: Observable<string>;

  constructor(private playerState: PlayerStateService) { }

  ngOnInit() {
    this.playerState$ = this.playerState.state$;
  }

}

  

这是您推荐的Working Sample StackBlitz