Angular7中訂閱MQTT

我的版本
Angular CLI: 7.2.1
Node: 10.14.1
OS: win32 x64
Angular: 7.2.0

嘗試使用
ngx-mqtt 
發現Mac可以順利載下
但我的開發環境是Windows
則會有許多相依問題

 

所以使用另一個library

ng2-mqtt 

npm i ng2-mqtt

在 ts中

  private _client: Paho.MQTT.Client;

  public constructor() {
    this._client = new Paho.MQTT.Client("zzzz.wevbsa.com", 0022, "Real")

    this._client.onConnectionLost = (responseObject: Object) => {
         console.log('Connection lost : ' + JSON.stringify(responseObject));
    };

    this._client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log( message.payloadString);
    };

    this._client.connect({ onSuccess: this.onConnected.bind(this) });
  }

  private onConnected(): void {
    this._client.subscribe('Json/Hsinchu/Attendance', { qos: 1 });
    console.log('Connected to broker.');
    this._client.onConnectionLost = (responseObject: Object) => {
      console.log('Connection lost : ' + JSON.stringify(responseObject));
    };
  }

這樣就可以訂閱MQTT的資料囉!


參考文件
https://www.sakib.ninja/angular2-with-mqtt/