如何在角度2中访问VideoJs函数中的成员变量和方法?

时间:2017-05-30 05:50:53

标签: javascript angular typescript video.js

我在角度项目中使用videojs插件。我试图访问videojs方法中的值和方法,但它在组件初始化时显示未定义的值。我试图在ngAfterViewInit中调用videojs方法,但它仍然没有在videojs方法中显示组件的值。我可以在videojs方法中显示变量值吗?谁能帮我?

组件代码:

import {Component,OnInit} from '@angular/core';
declare var videojs :any;

@Component({
  selector: 'app-play-video',
  templateUrl: './play-video.component.html',
  styleUrls : [] 
 })
export class PlayVideoComponent implements OnInit{
public videoJSplayer :any;
public videoUrl :string;

constructor(){
this.videoUrl = 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4';
}
showValues(){
console.log("show Values method called"); 
}
  ngOnInit() {
    this.videoJSplayer = videojs(document.getElementById('play_video_id'), {}, function() { 
          console.log(this.videoUrl);  // here the video url value is undefined
          this.showValues(); // this also undefined
          this.play();
          }
    }
  }

play-video.component.html:

<video id="play_video_id" class="video-js vjs-default-skin vjs-big-play-centered"
  controls preload="auto" width="640" height="264"
  poster="http://video-js.zencoder.com/oceans-clip.png"
  data-setup='{"example_option":true}'>
  <source [src] = videoUrl  type="video/mp4" />
</video>

1 个答案:

答案 0 :(得分:1)

您必须使用ES6 arrow functions进行回调才能在回调中获得正确的this上下文。当您使用function() {}语法时,this内部将根据调用上下文而有所不同:

this.videoJSplayer = videojs(document.getElementById('play_video_id'), {}, () => { 
          // `this` will point to the current `PlayVideoComponent` instance
     }
)