I am a beginner with Typescript and I am currently working on using Angular2 to develop a Web Midi application. However, I am facing some difficulties in understanding certain errors that I encounter. I believe that I should be placing the Midi functions within a Service, but please correct me if I am mistaken.
The code snippet below works perfectly fine when the midi variable and the onMIDIMessage function are placed outside:
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);
}
}
Everything is functional and I can successfully print incoming MIDI messages with this setup. However, what baffles me is that when I move the onMIDIMessage function and the midi variable inside the MidiService class, Chrome throws an error. Can anyone explain why this occurs?
midi.service.ts:24 Uncaught (in promise) TypeError: Cannot read property >'onMIDIMessage' of undefined at MidiService.onMIDISuccess (http://localhost:3000/app/midi.service.js:27:57)
var midi:any;
// Code snippet that causes issues
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
The methods are called in the app.component.ts file.
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();
}
}