我在我的应用程序中使用 Angular 2。我使用 getUserMedia 来访问网络摄像头。如果网络摄像头可用,则调用成功函数;如果网络摄像头不可用,则调用失败函数。检查下面的功能。
var n = <any>navigator;
n.getUserMedia = n.getUserMedia || n.webkitGetUserMedia || n.mozGetUserMedia || n.msGetUserMedia;
n.getUserMedia({video: true, audio:true}, this.onSuccess, this.onFail);
我定义了一个变量 isCamera : boolean
。
export class CameraComponent implements OnInit {
public isCamera: boolean;
...
}
我已在 onSuccess
函数中将此变量设置为 true,在 onFail
函数中将此变量设置为 false。但这给出了错误。我无法在回调 onSuccess 和 onFail 函数中设置值。我这两个函数的代码是
public onSuccess(){
this.isCamera = true;
}
public onFail(){
this.isCamera = false;
}
任何人都可以告诉如何将 true
值分配给 onSuccess
函数中的 isCamera
函数吗?
我收到此错误:-
未捕获的类型错误:无法设置未定义的属性“isCamera”
最佳答案
这里有两件事,您应该真正使用 mediaDevices 接口(interface)中的 getUserMedia,不推荐直接在导航器上使用 ( https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia )
之所以不能设置,是因为在回调中,“this”不是你想象的那样。因此,要么在回调中使用箭头函数,要么将回调绑定(bind)到“this”。
箭头函数:
n.getUserMedia({video: true, audio:true}, () => this.isCamera = true, () => this.camera = false);
绑定(bind):
n.getUserMedia({video: true, audio:true}, this.onSuccess.bind(this), this.onFail.bind(this));
关于javascript - 如何更改 Angular 2中getUserMedia回调函数中的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42485800/