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);
}
...
}
可以了!
【版权声明】本博文著作权归作者所有,任何形式的转载都请联系作者获取授权并注明出处!
【重要说明】博文仅作为本人的学习记录,论点和观点仅代表个人而不代表技术的真理,目的是自我学习和有幸成为可以向他人分享的经验,因此有错误会虚心接受改正,但不代表此刻博文无误!
【博客园地址】粘你一身大鼻嘎 : http://www.cnblogs.com/wjw1014
【CSDN地址】粘你一身大鼻嘎 : https://wjw1014.blog.csdn.net/
【Gitee地址】粘你一身大鼻嘎 :https://gitee.com/wjw1014
【重要说明】博文仅作为本人的学习记录,论点和观点仅代表个人而不代表技术的真理,目的是自我学习和有幸成为可以向他人分享的经验,因此有错误会虚心接受改正,但不代表此刻博文无误!
【博客园地址】粘你一身大鼻嘎 : http://www.cnblogs.com/wjw1014
【CSDN地址】粘你一身大鼻嘎 : https://wjw1014.blog.csdn.net/
【Gitee地址】粘你一身大鼻嘎 :https://gitee.com/wjw1014