【问题标题】:Problems trying to subscribe in a MQTT topic - Angular 5尝试订阅 MQTT 主题的问题 - Angular 5
【发布时间】:2018-06-02 19:59:48
【问题描述】:

我正在尝试使用 Angular 5 订阅 MQTT 主题,我正在使用 ng2-mqtt。 创建我的客户端后,我尝试连接,这就是问题开始的时候。我收到此错误:AMQJS0012E Invalid type undefined for onSuccess

有谁知道我做错了什么?

import { Component, OnInit } from '@angular/core';


import {Paho} from 'ng2-mqtt/mqttws31';



@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {

  client;

  constructor(){}

  ngOnInit() {
    this.client = new Paho.MQTT.Client('m2m.eclipse.org', 1883, 
    '_32fc96dd776142e6ba1a95116d09064f');

    this.client.connect({onSuccess: this.onConnected()})
  }

  onConnected() {
    console.log("Connected");
    this.client.subscribe("/cmd1234")
  }

 }

这是我的浏览器控制台:

【问题讨论】:

    标签: angular typescript mqtt


    【解决方案1】:

    您正在分配返回值undefined

    this.client.connect({onSuccess: this.onConnected()})
    

    您需要删除 () 以便分配功能

    this.client.connect({onSuccess: this.onConnected})
    

    您在函数中使用了this 引用。

    onConnected() {
       console.log("Connected");
       this.client.subscribe("/cmd1234")
    }
    

    当您使用 this 引用时,请确保您使用 bind 以确保它持续存在。

    this.client.connect({onSuccess: this.onConnected.bind(this)})
    

    我不会做上述任何事情。我会改用 TypeScript 匿名函数。

    this.client.connect({onSuccess: () => this.onConnected() })
    

    【讨论】:

    • 我做到了,但后来我得到: WebSocket 连接到 'ws://m2m.eclipse.org:1883/mqtt' 失败:WebSocket 握手期间出错:net::ERR_CONNECTION_RESET 知道为什么吗?
    【解决方案2】:

    我解决了。我只是更改了 MQTT 服务器的主机,没有传递端口,然后一切正常

    ngOnInit() {
       this.client = new Paho.MQTT.Client('ws://iot.eclipse.org/ws','_32fc96dd776142e6ba1a95116d09064f');
    
       this.client.connect({onSuccess:()=> this.onConnected()})
       this.client.onMessageArrived = this.onMessage.bind(this);
    

    }

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多