How to use webrtc in Angular 2?

You should include adapter.js: https://github.com/webrtc/adapter

Basically, you could just use the code from another answer:

navigator.getUserMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

Although, there are even more WebRTC-functions that would remain inaccessible in that case. So, including adapter.js is more correct way. Moreover, it is maintained and updated by Google (one of the biggest WebRTC contributors).


following is how I used webrtc in Angular 4 -->

import {Component, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  @ViewChild('hardwareVideo') hardwareVideo: any;

  _navigator = <any> navigator;
  localStream;

  ngOnInit() {

    const video = this.hardwareVideo.nativeElement;
    this._navigator = <any>navigator;

    this._navigator.getUserMedia = ( this._navigator.getUserMedia || this._navigator.webkitGetUserMedia
    || this._navigator.mozGetUserMedia || this._navigator.msGetUserMedia );

    this._navigator.mediaDevices.getUserMedia({video: true})
      .then((stream) => {
        this.localStream = stream;
        video.src = window.URL.createObjectURL(stream);
        video.play();
    });

  }

  stopStream() {
    const tracks = this.localStream.getTracks();
    tracks.forEach((track) => {
      track.stop();
    });
  }

}

template:

<div style="text-align:center">
  <h1>
    Welcome to my webRTC demo app!
  </h1>
  <button (click)="stopStream()">Stop Streaming</button>
  <video #hardwareVideo autoplay></video>
</div>

You have made a couple of mistakes:

1) getUserMedia delivers a Promise, there is lack of a .then

2) Use navigator.mediaDevices.getUserMedia instead of navigator.getUserMedia

3) The line video = document.querySelector('video'); needs to be inside ngOnInit

4) As a consequence of 3) you need to declare video: HTMLVideoElement; in the first section.

5) Use this.video.srcObject = stream to put the stream on the HTMLVideoElement

When you put everything together you will get the following code:

import {Component,OnInit} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `
    <h1>Realtime communication with WebRTC</h1>
    <video autoplay></video>
  `
})
export class App {

  video: HTMLVideoElement;
  constraints = { audio: false, video: true };

  constructor() {}

  ngOnInit(): void {
    this.video = document.querySelector('video');
    navigator.mediaDevices.getUserMedia(this.constraints).then(
      stream => {
        this.video.srcObject = stream
      },
      error => {
        console.log('Error: ' + error);
      });
  }
}