javascript - MQTT 与 Ionic 3 的连接

标签 javascript angular typescript ionic3 mqtt

我需要在我的 Ionic 3 应用程序中使用发布订阅方法。

我关注了this page .

有什么方法可以将 MQTT 与我们的 Ionic 3 应用程序关联起来?如果是,怎么会这样? 我究竟需要怎样做才能成功连接?

我使用安装了ng2-mqtt服务

npm install ng2-mqtt --save

这是我的代码:

index.html

<script src="cordova.js"></script>
<script src="node_modules/ng2-mqtt/mqttws31.js" type="text/javascript"></script>

home.ts

import {Paho} from 'mqttws31'

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

      private _client: Paho.MQTT.Client;

      constructor(public paho: Paho) {

      }
         this._client = new Paho.MQTT.Client("52.66.30.178", 1883, "path", "someclient_id");

        this._client.onConnectionLost = (responseObject: Object) => {
          console.log('Connection lost.');
        this.getServerMessage();

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

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

我仍然无法让它工作。

任何建议和更改都会对我有所帮助。我卡住了,请执行。

最佳答案

在搜索和尝试不同的东西一段时间后,我找到了这个解决方案,如果你想在你的项目中使用 MQTT,你可以使用这个库。

使用 npm install ngx-mqtt --save 安装它

用法:app.module.ts

import { Observable } from 'rxjs/Observable';
import {
  IMqttMessage,
  MqttModule,
  MqttService
} from 'ngx-mqtt';

export const MQTT_SERVICE_OPTIONS = {
  hostname: '13.127.53.13',
  port: 9001,
  path: '/mqtt'
};

export function mqttServiceFactory() {
  return new MqttService(MQTT_SERVICE_OPTIONS);
}

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    MqttModule.forRoot({
      provide: MqttService,
      useFactory: mqttServiceFactory
    }),
    IonicModule.forRoot(MyApp)
  ]

然后您可以在您的页面中使用它,例如:(例如:home.ts 文件)

import { IMqttMessage, MqttModule, MqttService } from 'ngx-mqtt';
import { Observable } from 'rxjs/Observable';

export class HomePage  {

constructor( private _mqttService: MqttService)
{
   this._mqttService.observe('home/door').subscribe((message: MqttMessage) => 
   {
   this.sensor1 = message.payload.toString();
   console.log(this.sensor1);
   });
}

 publishMessage()
 {
  this._mqttService.unsafePublish("home/button", "on", {qos: 0, retain: false});
 }

有关此库的更多信息: https://github.com/sclausen/ngx-mqtt

关于javascript - MQTT 与 Ionic 3 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48702611/

相关文章:

angular - 在 mat-table 的表标记中使用 multiTemplateDataRows 和 formArrayName 时出错

javascript - Angular 4 : TypeError: this. 函数不是函数

javascript - 正则表达式:替换模式内的字符串作为函数的返回值

javascript - 属性值不通过对象字面量定义应用

angular - “environment.ts”不在 'rootDir' Angular 库构建错误下

node.js - Visual Studio Code 在悬停时不显示最新版本的 npm 包

javascript - 对给定初始值的对象数组进行排序,使其始终排在第一位

jquery - 在 TypeScript 中使用 jQuery $ 前缀

javascript - jQuery.cookie : no update of the cookie despite a very simple code

javascript - HSL 颜色到底应该怎么写?