我需要在我的 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/