角度mqtt更新值,每个接收消息

时间:2020-10-01 17:01:27

标签: angular mqtt

我将mqtt protocolwebsocket一起使用,因此我使用浏览器显示我的接收值。 问题是,当我手动执行函数console.log时,我可以(在我的示例中)收到subscribeNewTopic()消息,但是如果我收到另一条消息,由于我是手动运行该函数,因此不会收到新消息。我想要一个函数,它在每次接收到新值时都会console.log结果....是否可以?

这是我的角函数:

  subscribeNewTopic(): void {
    console.log('inside subscribe new topic')
    this.subscription = this._mqttService.observe(this.topicname).subscribe((message: IMqttMessage) => {
      this.msg = message;
      console.log('msg: ', message)
      console.log(message.payload.toString())
      this.logMsg('Message: ' + message.payload.toString() + '<br> for topic: ' + message.topic);
    });
    this.logMsg('subscribed to topic: ' + this.topicname)
  }

  logMsg(message): void {
    this.msglog.nativeElement.innerHTML += '<br><hr>' + message;
  }

1 个答案:

答案 0 :(得分:0)

我认为,您的代码应该可以正常工作。在代码的这一部分中:

this.subscription = this._mqttService.observe(this.topicname).subscribe((message: IMqttMessage) => {
      this.msg = message;
      console.log('msg: ', message)
      console.log(message.payload.toString())
      this.logMsg('Message: ' + message.payload.toString() + '<br> for topic: ' + message.topic);
});

this.msg应该具有主题的最新值。

如果您需要更多帮助,可以尝试通过“因为我手动运行该功能”来进一步精确化您的意思。
另外,请尝试阅读本行会link,这可能会有所帮助。

相关问题