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);
}
...
}
可以了!