Ionic 使用 MQTT

Ionic 使用 MQTT

Ionic 使用 mqtt ,有一个比较好用的插件,用起来还不错,记录一下下!
网址:https://www.npmjs.com/package/ionic-mqtt

插件安装

npm install ionic-mqtt --save

在 app.module.ts 里面导包注入依赖

import { IonicMqttModule, MQTTService } from 'ionic-mqtt';

@NgModule({
  ...,
  imports: [
    ...,
    IonicMqttModule
  ],
  providers: [
    ...,
    MQTTService
  ],
});

export class AppModule {}

使用

在需要使用 mqtt 的页面

import { MQTTService } from 'ionic-mqtt';

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

export class HomePage {

  private _mqttClient: any;

  private MQTT_CONFIG: {
    host: string,
    port: number,
    clientId: string,
  } = {
    host: "test.mosquitto.org",
    port: 8081,
    clientId: "mqtt",
  };

  private TOPIC: string[] = [];

  constructor(private mqttService: MQTTService) {
  }

  ngOnInit() {
    this._mqttClient = this.mqttService.loadingMqtt(this._onConnectionLost, this._onMessageArrived, this.TOPIC, this.MQTT_CONFIG);
  }

  private _onConnectionLost(responseObject) {
    // connection listener
    // ...do actions when connection lost
    console.log('_onConnectionLost', responseObject);
  }

  private _onMessageArrived(message) {
    // message listener
    // ...do actions with arriving message
    console.log('message', message);
  }

  ...


  // public function for sending and publishing mqtt messages

  public sendMessage() {
    console.log('sendMessage')
    this._mqttService.sendMessage(TOPIC, MESSAGE);
  }

  public publishMessage() {
    console.log('publishMessage')
    this._mqttService.publishMessage(TOPIC, MESSAGE);
  }

  ...

}

在这里插入图片描述

可以了!

posted @   叫我+V  阅读(642)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示