I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file:
import { Component } from '@angular/core';
import * as mqtt from 'mqtt';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private client: mqtt.Client;
ngOnInit(): void {
this.initializeMQTTClient();
}
public initializeMQTTClient() {
console.log('Attempting connection');
this.client = mqtt.connect('ws://mqttBroker.de:1882');
this.client.addListener('connect', this.onConnect);
this.client.addListener('message', this.onMessage);
}
private onConnect() {
console.log('Connected successfully');
this.client.subscribe('/broker/response/clientID');
this.client.publish('/providers', '{...Message...}');
}
private onMessage(args: any[]) {
console.log(args[0]);
console.log(args[1]);
}
}
The connection is established successfully as I can see the 'connected' message in the log, but then I encounter an error
Cannot read property 'subscribe' of undefined
I am puzzled as to why the client variable is not accessible in the onConnect method. I believe there might be some fundamental TypeScript concept that I am missing, but despite my efforts, I haven't been able to pinpoint the exact issue.