语音识别回调未在回调中定义



我正试图使用语音识别实例,在成功回调中,我正尝试使用语音术语来调用api。问题是成功回调"this"被视为语音识别对象的实例,而不是类实例。

接下来,我浏览了一些解决方案,将this实例复制到that变量中,并调用函数。现在函数调用正在工作,但所有角度绑定都失败了。代码片段如下:

voiceSearch() {
console.log('listening');
if ("webkitSpeechRecognition" in window) {
const vSearch = new webkitSpeechRecognition();
vSearch.continuous = false;
vSearch.interimresults = false;
vSearch.lang = 'en-US';
vSearch.start();
let that = this;
vSearch.onresult = function (e) {
voiceHanlder.value = e.results[0][0].transcript;
that.searchTerm = voiceHanlder.value;
vSearch.stop();
that.searchProducts(that.searchTerm); // unable to use this code without using that = this
}
vSearch.onerror = function (e) {
console.log(e);
vSearch.stop();
}
}
else {
console.log('Your browser does not support speech recognition');
}
}
searchProducts(searchTerm: string) {
this.searchMade = true;
this.getProducts(searchTerm).subscribe(resp => {
this.searchedProducts = resp['records'];
this.searchValue = "Now showing the searched products";
console.log(this.searchedProducts);
})
}

我把代码改成:

vSearch.onresult ( (e) => {
voiceHanlder.value = e.results[0][0].transcript;
that.searchTerm = voiceHanlder.value;
vSearch.stop();
that.searchMade = true;
that.searchCvsProducts(that.searchTerm);
that.listeningOn = false;
//voiceSearchForm.submit();
})

但是我得到了一个类似vSearch.onResult的错误,它不是一个函数。

我们可以使用一个胖箭头运算符来避免那个=这个代码吗。

您需要使用na箭头函数来捕获this上下文。

vSearch.onresult = (e) => {
voiceHanlder.value = e.results[0][0].transcript;
this.searchTerm = voiceHanlder.value;
vSearch.stop();
this.searchProducts(this.searchTerm);
}

我建议您阅读TypeScript手册中的函数一章,它很好地解释了this如何在函数中工作。

最新更新