Sudhanshu sharma Sudhanshu sharma -4 years ago 242
Javascript Question

how to change variable value in callback function of getUserMedia in angular 2

I am using angular 2 for my application. I have used getUserMedia to access webcam. If webcam is available then success function is called and if webcam is not available then fail function is called. check function below.

var n = <any>navigator;
n.getUserMedia = n.getUserMedia || n.webkitGetUserMedia || n.mozGetUserMedia || n.msGetUserMedia;
n.getUserMedia({video: true, audio:true}, this.onSuccess, this.onFail);

I have one variable
isCamera : boolean
defined .

export class CameraComponent implements OnInit {
public isCamera: boolean;

I have set this variable to true in
function and false in
function. But this is giving error. I am not able to set the value in callback onSuccess and onFail function. my code for these two function is

public onSuccess(){
this.isCamera = true;

public onFail(){
this.isCamera = false;

Can anyone tell how to assign
value to
function in
function ?
I am getting this error :-
Uncaught TypeError: Cannot set property 'isCamera' of undefined

Answer Source

2 things here, you should really use getUserMedia from the mediaDevices interface, directly on navigator is deprecated (

The reason why you can't set it is because in the callbacks, 'this' isn't what you think it is. So either use arrow functions in your callback or bind the callbacks to 'this'.

Arrow functions:

n.getUserMedia({video: true, audio:true}, () => this.isCamera = true, () => = false);


n.getUserMedia({video: true, audio:true}, this.onSuccess.bind(this), this.onFail.bind(this));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download