AngularJS中navigator.permissions.query回调无法访问类变量怎么办?
问题解决方案
问题核心是普通function回调的this上下文指向错误:then里的普通function会创建独立的执行上下文,这里的this不再指向你的组件实例,因此无法访问this.psp、this.toastr这类类变量。
有两种常用解决方法:
方法一:使用箭头函数
箭头函数不会绑定自身的this,会继承外层作用域的this(即你的组件实例),直接替换回调函数即可:
public recordAnswer(event: any) { this.recording = true; this.toastr.error('Something went wrong. Try again.'); navigator.permissions.query({name: 'microphone'}).then((result) => { console.log(result); if (result.state == 'granted') { // start recording audio } else if (result.state == 'prompt') { } else if (result.state == 'denied') { console.log(this.psp); // 现在可正常访问类变量 this.toastr.error('请授予麦克风权限后再尝试'); } result.onchange = () => {}; // 此处也建议换成箭头函数,避免同类问题 }); }
方法二:提前保存组件的this引用
在回调外部将组件实例的this赋值给一个变量(比如that),在回调里用这个变量访问类变量:
public recordAnswer(event: any) { this.recording = true; this.toastr.error('Something went wrong. Try again.'); const that = this; // 保存组件实例的引用 navigator.permissions.query({name: 'microphone'}).then(function (result) { console.log(result); if (result.state == 'granted') { // start recording audio } else if (result.state == 'prompt') { } else if (result.state == 'denied') { console.log(that.psp); // 使用that访问类变量 that.toastr.error('请授予麦克风权限后再尝试'); } result.onchange = function () {}; }); }
内容的提问来源于stack exchange,提问作者Dula
相关产品推荐
相关产品推荐

