在我的 Angular 项目中,我有一个有 2 个成员函数的类。在第一个函数中,我有 2 个级别的回调。在第一个回调中,我需要添加第二级事件回调。在这个第二级回调中,我需要能够调用顶级类的第二个成员函数。我尝试了https://www.pluralsight.com/guides/javascript-callbacks-variable-scope-problem中建议的技巧。它对我不起作用。目前我正在尝试Angular2 - 如何从应用程序外部调用组件函数,该应用程序讨论 ngZone 以公开组件成员函数。
我的代码的详细信息:
我有一个用 Angular 8 编写的音频处理“AudioProcessingUtility”类。在它的 Init() 中,我正在初始化 MediaRecorder。我正在为“datavailable”事件添加一个监听器。此侦听器函数需要从“主”类调用我的实用程序函数。即它必须从回调进入父类的范围。
代码:
export class AudioProcessingUtility {
//integrated componet-level properties
//video conf specific properties
localAudioStreamStdObj: MediaStream;
mediaRecorder: any;
agoraService: any;
localStream: Stream;
constructor() {}
private StreamInit() { //top-level member function to init
this.localStream.init(() => {
this.agoraService.client.publish(this.localStream, function (err) { //This triggers "stream-published" event.
console.log("Publish local stream error: " + err);
});
this.agoraService.client.on('stream-published', function (evt) {
console.log("Publish local stream successfully");
this.localAudioStreamStdObj = new MediaStream([evt.stream.getAudioTrack()]); //Specific details of media API
this.mediaRecorder = new MediaRecorder(this.localAudioStreamStdObj, { mimeType: 'audio/webm' }); //Specific details of media API
this.mediaRecorder.start(4000);
this.mediaRecorder.addEventListener("dataavailable", event => { //Triggered every 4 seconds.
console.log("callbackfn: data vailable");
console.log(event.data);
//MY NEED
this.audioProcessorCallback(event.data); //top-level member function be called
});
this.mediaRecorder.addEventListener("stop", () => {
});
////end real time grab
});
}, function (err) {
console.log("failed", err);
});
}//end of stream Init function
public audioProcessorCallback(eventdatavailable) { //Top-level function to be called from 2nd-level callback
console.log("My processing");
//Do REST API calls. Based on internal states of the class, do specific processing
}
} //end of AudioProcessingUtility
问题:
触发 dataavailable 事件。但我在以下几行中遇到错误。它给出错误ERROR TypeError: this.audioProcessorCallback is not a function
//MY NEED
this.audioProcessorCallback(event.data); //top-level member function be called is not recognized.
我知道这是因为 - 在回调内部,它无法找到“this context”。请建议我如何调用我的类函数,而不必将所有内容都放在内联回调函数中,这对我来说是不切实际的。
编辑:我重写了问题以提供显示完整代码并更改了描述。提前致谢。