I am trying to use Angular-Speech-Recognition in Angular application. Below are my html and component ts code. My speech is correctly getting assigned to this.message
. My requirement is, after I complete the speech, I want to call this.getSearchResults(this.message);
. But whats happening is for each word in my speech the function call this.getSearchResults(this.message)
is happening.
For example, if I speak, "I forgot my password"
, I expect this.getSearchResults(this.message)
to be called once with this.message
as "I forgot my password"
. But whats happening is 4 times the function is getting called, as there are 4 words in my speech (for each word the function getSearchResults
is getting triggered). How can I fix it?
<fa-icon
[icon]="faMicrophone"
class="microphone-icon"
(click)="listenSpeech()">
</fa-icon>
listenSpeech() {
this.speechSrv
.listen()
.pipe(resultList)
.subscribe((list: SpeechRecognitionResultList) => {
this.message = list.item(0).item(0).transcript;
this.getSearchResults(this.message);
});
}
It looks like you never unsubscribe so with every click you're making another subscription. Maybe you want to use take(1)
to ensure each .subscribe
is going to be trigger at most once?
this.speechSrv
.listen()
.pipe(resultList) // Don't know what this is so you might put `take(1)` here instead of using two `pipe()` calls
.pipe(take(1))
.subscribe((list: SpeechRecognitionResultList) => {
this.message = list.item(0).item(0).transcript;
this.getSearchResults(this.message);
});