I am trying to use the speech recognition instance and inside the success callback I am trying to use the speech term to call an api. The problem is that the success call back 'this' is being taken as the instance of speech recognition object and not the class instance.
Next I went through some of the solutions and copied the this instance into a that variable and called the functions. Now the function call is working but all the angular bindings are failing. The code snippet is as below:
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);
})
}
I changed the code to:
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();
})
But I am getting an error like vSearch.onResult is not a function.
Can we use a fat arrow operator to avoid the that = this code.