我正在尝试在我的 Angular 应用程序中接收一些 mqtt 消息。 不幸的是,它不起作用。 这是我的代码(我遵循的是:https://sclausen.github.io/ngx-mqtt/): 在 app.module.ts 中:
import {
IMqttMessage,
MqttModule,
IMqttServiceOptions,
MqttService
} from 'ngx-mqtt';
export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {
hostname: 'localhost',
port: 9001,
path: '/mqtt'
};
在app.component.ts中:
subscription: Subscription | undefined;
constructor(private mqttService: MqttService) {
this.serial = new NgxSerial(this.dataHandler);
console.log(mqttService)
this.subscription = this.mqttService.observe('my/topic').subscribe((message: IMqttMessage) => {
this.message = message.payload.toString();
console.log('Received message:', message.payload.toString());
});
}
public unsafePublish(topic: string, message: string): void {
this.mqttService.unsafePublish(topic, message, { qos: 1, retain: true });
}
public ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
以下是我尝试向应用程序发送消息:
有什么建议吗?谢谢!
那么在app.module.ts中我建议你不要放连接参数,只放代码结构。
然后您可以将所有逻辑放入组件中。告诉我你是否已经解决了,否则我会帮助你。