1

I'm using a cordova speech recognition plugin (https://github.com/pbakondy/cordova-plugin-speechrecognition) which the method will return what the user has spoken. However if I console.log(startSpeechRecognition()), the return results will not be executed and it will return as 'undefined'

startSpeechRecognition() {
var options = {
  language:'en-US',
  showPopup:false
};

this.speechRecognition.startListening(options) 
  .subscribe(
    (results: Array<string>) => {return results},
    (onerror: string) => (console.log("Error: "+onerror))
  );
}

I've tried another solution (Angular 2: Convert Observable to Promise) by using toPromise() but I still get the same result. Any help is greatly appreciated.

Index
  • 63
  • 4
  • At the time the console.log is executed, the `.subscribe` function isn't called. So I would use a log (and a proper callback function to make it work) instead of `return results`. – sandrooco May 16 '18 at 06:52

2 Answers2

1
this.speechRecognition.startListening(options) 
  .subscribe(
    (results: Array<string>) => {return results},
    (onerror: string) => (console.log("Error: "+onerror))
  );

This won't produce anything.

Try this instead.

this.speechRecognition.startListening(options) 
  .subscribe(
    (results: Array<string>) => {
      console.log(results);
    },
    (onerror: string) => (console.log("Error: "+onerror))
  );
0

Because Angular calls the subscribe method asynchronously, the function within console.log(startSpeechRecognition()) will return undefined even before the observable has been subscribed.

You can apply console.log() inside the subscribe:

this.speechRecognition.startListening(options) 
.subscribe(
(results: Array<string>) => {
 console.log(results);
 return results;
 },
(onerror: string) => (console.log("Error: "+onerror))
);

or add a add() method after subscription:

let obj = [];
this.speechRecognition.startListening(options) 
.subscribe(
(results: Array<string>) => {
 obj = results;
 },
(onerror: string) => (console.log("Error: "+onerror))
).add(()=>
{ 
//Use your object here
 console.log(obj);
 });
Prachi
  • 3,478
  • 17
  • 34