简体   繁体   中英

Angular 2/4 communicate with a third party library

I'm using simple-peer js for creating a video chat , the problem is that it is a third party library and it does not communicate to the angular system such as angular does not track property binding changes etc. here is the code

export class AppComponent implements OnInit, OnChanges {
  @ViewChild('myVideo') myVideo:any;

  texttoken :string;

  targetpeer: any;
  peer: any;
  n = <any>navigator;

  ngOnInit() {


    let video = this.myVideo.nativeElement;
    let peerx: any;
    let jsonToken:any;
    this.n.getUserMedia = (this.n.getUserMedia || this.n.webkitGetUserMedia || this.n.mozGetUserMedia || this.n.msGetUserMedia);
    this.n.getUserMedia({video:true, audio:true}, function(stream) {
    peerx = new SimplePeer ({
      initiator: location.hash === '#init',
      trickle: false,
      stream:stream
    })

    peerx.on('signal', function(data) {
      console.log(JSON.stringify(data)); 
      jsonToken = JSON.stringify(data);
      this.targetpeer = data;
    })

    peerx.on('data', function(data) {
      console.log('Recieved message:' + data);
    })

    peerx.on('stream', function(stream) {
      video.src = URL.createObjectURL(stream);
      video.play();
    })

    }, function(err){
    console.log('Failed to get stream', err);
    });


    setTimeout(() => {
      this.peer = peerx;
      this.texttoken = jsonToken;
      console.log(this.peer);
    }, 1000);

  }         
}

so the only thing I need is to get the data from peerx.on('signal' call back , and I need to get delayed data sometimes, as you can see I only able to get data after 1 second (see the timeOut function I'm getting JsonToken), the only solution I could think of is to create an infinite loop to get updated data from there every x seconds , do you have any other better ideas? how do you handle third party libs in angular 2/4? Thank You

Assuming peerx is the global variable for your third party library, you have to put this before your component decorator :

declare var peerx: any;

this way, you can access all the properties of your third-party library. If you have some time to lose, you can even write the definition file for Typescript, meaning that your IDE will have an autocompletion on it (and you will need to import it instead of declare it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM