1

I want to add a speech recognition in Angular 7 using the webkitSpeechRecognition. I get the value from the speech but the problem is that I can't use it outside of vSearch.onresult.

I tried to use the variable "result" in the getResult() function and send a get request but it says it's undefined;

Here is my code in the ts.

voiceSearch() {
    let voiceHandler = this.hiddenSearchHandler.nativeElement;
    if ("webkitSpeechRecognition" in window) {
        const vSearch = new webkitSpeechRecognition();
        vSearch.continuous = false;
        vSearch.interimresults = false;
        vSearch.lang = 'en-US';
        vSearch.start();
        vSearch.onresult = function(e) {
            voiceHandler.value = e.results[0][0].transcript;
            this.result = e.results[0][0].transcript;
            vSearch.stop();
        }
    } else {
        alert("Your browser does not support voice recognition!");
    }
}

getResult() {
    console.log(this.result);
}
Daniel Ormeño
  • 2,743
  • 2
  • 25
  • 30
  • How is `voiceSearch` being called? If it is in an event listener, `this` is out of scope. Turn `voiceSearch` into an arrow function: `voiceSearch = () => {` – Andrew Oct 03 '19 at 22:20
  • I am calling voiceSearch on button click. Do you mean like this? `voiceSearch = () => { let voiceHandler = this.hiddenSearchHandler.nativeElement; if ("webkitSpeechRecognition" in window) {` I still don't get the value in getResult() – Anastasija G Oct 03 '19 at 22:38
  • Angular may work differently from how I think it does then. `class` syntax in JavaScript creates traditional functions using the `function` syntax, which will always be out of scope when calling inside an event listener. But creating a method using the arrow function syntax, `= () =>` =, which has no `this`, will not have that issue. – Andrew Oct 03 '19 at 22:57

0 Answers0