AMQJS0005E内部错误。错误消息:无法读取属性'订阅'未定义的
我在我的应用程序中包含了eclipse paho javascript客户端库。 连接已建立,但我无法订阅主题。 这是我用过的代码..
import { Component } from '@angular/core';
import { NavController, NavParams ,MenuController } from 'ionic-angular';
import { Setuser } from '../../providers/setuser';
import { Platform } from 'ionic-angular';
import { Paho} from 'ng2-mqtt/mqttws31';
/*
Generated class for the Usershome page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
selector: 'page-usershome',
templateUrl: 'usershome.html'
})
export class UsershomePage {
client :any;
message :any;
constructor(public navCtrl: NavController, public navParams: NavParams,public menu:MenuController,public setUserProvider: Setuser,public platform:Platform) {
this.menu.open();
}
ionViewDidLoad() {
this.menu.enable(true);
console.log('ionViewDidLoad UsershomePage');
}
exitApp(){
console.log("----------");
this.platform.exitApp();
}
connectToMqtt(){
this.client = new Paho.MQTT.Client("test.mosquitto.org",8080,"abc");
// set callback handlers
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived;
// connect the client
this.client.connect({onSuccess:this.onConnect});
}
// called when the client connects
onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
this.client.subscribe("mitsuruog");
this.message = new Paho.MQTT.Message("Hello");
this.message.destinationName = "World";
this.client.send(this.message);
}
// called when the client loses its connection
onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
}
}

答案 0 :(得分:1)
通过修改行
可以解决您的直接问题this.client.connect({onSuccess:this.onConnect.bind(this)});
或者,令您惊讶的是,删除this.
和client
引用前面的所有message
。
您应该了解JavaScript中this
的确切含义。与Java或C#不同。要了解删除的原因,请了解闭包和箭头函数。
良好的起点(您的问题实际上可能被标记为此问题的副本): How to access the correct `this` context inside a callback?