In package.json
add,
"ng2-mqtt": "^0.1.2"
npm install
it will install dependencies.
Now in your component or class import,
import {Paho} from 'ng2-mqtt/mqttws31';
Now do whatever you want to do.
Like,
import {Paho} from 'ng2-mqtt/mqttws31';
export class MqttConnection {
client;
constructor() {
this.client = new Paho.MQTT.Client('127.0.0.1', 8083, 'qwerty12345');
this.onMessage();
this.onConnectionLost();
this.client.connect({onSuccess: this.onConnected.bind(this)});
}
onConnected() {
console.log("Connected");
this.client.subscribe("123456");
this.sendMessage('HelloWorld');
}
sendMessage(message: string) {
let packet = new Paho.MQTT.Message(message);
packet.destinationName = "123456";
this.client.send(packet);
}
onMessage() {
this.client.onMessageArrived = (message: Paho.MQTT.Message) => {
console.log('Message arrived : ' + message.payloadString);
};
}
onConnectionLost() {
this.client.onConnectionLost = (responseObject: Object) => {
console.log('Connection lost : ' + JSON.stringify(responseObject));
};
}
}
Note : ng2-mqtt
library is a port of Paho's js library.
Docs : http://www.eclipse.org/paho/files/jsdoc/symbols/Paho.MQTT.Client.html