我正在尝试在Angular应用程序中使用Angular语音识别。下面是我的html和组件ts代码。我的演讲被正确地分配给了this.message
。我的要求是,在我完成演讲后,我想打电话给this.getSearchResults(this.message);
。但是,对于我演讲中的每个单词,函数调用this.getSearchResults(this.message)
都在发生。
例如,如果我说"I forgot my password"
,我希望this.getSearchResults(this.message)
被调用一次,this.message
作为"I forgot my password"
。但发生的事情是函数被调用了4次,因为我的演讲中有4个单词(每个单词都会触发函数getSearchResults
(。我该怎么修?
<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);
});
}
看起来你从未取消订阅,所以每次点击都会进行另一次订阅。也许您想使用take(1)
来确保每个.subscribe
最多触发一次?
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);
});