首页 > 解决方案 > Video in Angular - TypeError Issue

问题描述

I'm trying to do some basic video stream work in Angular. My code is below. Challenge is I keep getting and error that says... ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'video' of undefined TypeError: Cannot read property 'video' of undefined

Any suggestions would be appreciated.

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


@Component({
  selector: 'app-scanner',
  templateUrl: './scanner.component.html',
  styleUrls: ['./scanner.component.css']
})
export class ScannerComponent implements OnInit {
  @ViewChild('video') video: HTMLMediaElement;

  constructor() {}

  ngOnInit() {
    this.cameraCheck();
  }



  cameraCheck() {
    navigator.mediaDevices
      .getUserMedia({
        video: {
          facingMode: 'environment'
        }
      })
      .then(function(stream) {
        this.video.srcObject = stream;
        this.video.setAttribute('playsinline', 'true'); // required to tell iOS safari we don't want fullscreen
        this.video.play();
      });
  }
}
<div>
  <video #video></video>
</div>

标签: angulartypescripthtml5-video

解决方案


function(stream)承诺句柄中的 newgetUserMedia似乎没有得到正确的this参考。因此错误。将其更改为使用箭头功能应该可以解决问题。

例子:

cameraCheck() {
    navigator.mediaDevices
      .getUserMedia({
        video: {
          facingMode: 'environment'
        }
      })
      .then((stream) => {
        this.video.srcObject = stream;
        this.video.setAttribute('playsinline', 'true'); // required to tell iOS safari we don't want fullscreen
        this.video.play();
      });
  }
}

推荐阅读