我是Typescript的新手,我正在尝试使用Angular2创建一个Web Midi应用程序,但我在理解某些错误时遇到了一些麻烦。我相信我应该将Midi功能放在服务中,但如果我错了,请纠正我。
当midi变量和onMIDIMessage函数在
之外时,下面的示例有效var midi:any;
function onMIDIMessage(event) {
console.log("msg received", event);
}
export class MidiService {
onMidiInit() {
if (navigator.requestMIDIAccess) {
navigator.requestMIDIAccess({
sysex: false
}).then(this.onMIDISuccess, this.onMIDIFailure);
} else {
alert("No MIDI support in your browser.");
}
}
onMIDISuccess(midiAccess) {
console.log('MIDI Access Object', midiAccess);
midi = midiAccess;
console.log(midi);
var inputs = midi.inputs.values();
for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
input.value.onmidimessage = onMIDIMessage;
}
}
onMIDIFailure(e) {
console.log(e);
}
}
一切都很好,我可以打印出传入的MIDI信息。但是,我不明白的是,当onMIDIMessage函数和midi变量在MidiService类中时,Chrome会抛出错误。为什么会这样?
midi.service.ts:24 Uncaught(in promise)TypeError:无法读取属性>'onMIDIMessage'未定义在MidiService.onMIDISuccess(http://localhost:3000/app/midi.service.js:27:57)
var midi:any;
// Code that does not work
export class MidiService {
onMidiInit() {
if (navigator.requestMIDIAccess) {
navigator.requestMIDIAccess({
sysex: false
}).then(this.onMIDISuccess, this.onMIDIFailure);
} else {
alert("No MIDI support in your browser.");
}
}
onMIDISuccess(midiAccess) {
console.log('MIDI Access Object', midiAccess);
midi = midiAccess;
console.log(midi);
var inputs = midi.inputs.values();
for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
input.value.onmidimessage = this.onMIDIMessage;
}
}
onMIDIMessage(event) {
console.log("msg received", event);
}
onMIDIFailure(e) {
console.log(e);
}
}
--- EDIT
在app.component.ts文件中调用这些方法。
import {Component} from 'angular2/core';
import {MidiService} from './midi.service';
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>',
providers: [MidiService]
})
export class AppComponent {
constructor(midiService: MidiService) {
midiService.onMidiInit();
}
}
答案 0 :(得分:1)
看起来this
没有指向当前的类实例。
当您将当前类的方法作为回调传递时添加.bind(this)
:
input.value.onmidimessage = this.onMIDIMessage.bind(this);