【发布时间】:2019-01-24 06:50:12
【问题描述】:
我正在尝试使用语音识别实例,并且在成功回调中我正在尝试使用语音术语来调用 api。问题是成功回调“this”被视为语音识别对象的实例,而不是类实例。
接下来,我浏览了一些解决方案并将 this 实例复制到 that 变量中并调用了函数。现在函数调用正在工作,但所有角度绑定都失败了。代码sn-p如下:
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 is not a function。
我们可以使用粗箭头运算符来避免 that = this 代码吗?
【问题讨论】:
-
应该是
vSearch.onresult = (e) => { ... }。 -
@connorsFan - 我已经能够使用胖箭头以及 function.prototype.bind 但现在我看到一个问题,即 angular 在立即回调后没有更新它的绑定。然而,在我进行另一次搜索后,它也在做同样的事情。任何想法都一样。我可以手动触发绑定操作,但这并不能解释为什么它们不应该首先工作。如果我不做语音识别,那绝对没问题。
-
尝试按照this answer 中的建议将代码封装在
NgZone.run(() => { ... })中。
标签: angular typescript this