我使用了cordova语音识别插件(https://github.com/pbakondy/cordova-plugin-speechrecognition),该方法将返回用户所说的内容。但是,如果我是console.log(startSpeechRecognition()),则返回结果将不会被执行,并且将返回为' 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))
);
}
我通过使用toPromise()尝试了另一种解决方案(Angular 2: Convert Observable to Promise)但我仍然得到了相同的结果。非常感谢任何帮助。
答案 0 :(得分:1)
this.speechRecognition.startListening(options)
.subscribe(
(results: Array<string>) => {return results},
(onerror: string) => (console.log("Error: "+onerror))
);
这不会产生任何结果。
试试这个。
this.speechRecognition.startListening(options)
.subscribe(
(results: Array<string>) => {
console.log(results);
},
(onerror: string) => (console.log("Error: "+onerror))
);
答案 1 :(得分:0)
因为Angular异步调用subscribe方法,所以即使在订阅了observable之前,console.log(startSpeechRecognition())中的函数也将返回undefined。
您可以在subscribe:
中应用console.log()this.speechRecognition.startListening(options)
.subscribe(
(results: Array<string>) => {
console.log(results);
return results;
},
(onerror: string) => (console.log("Error: "+onerror))
);
或在订阅后添加add()方法:
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);
});