2017-02-16 129 views
0

AMQJS0005E內部錯誤。錯誤消息:無法讀取屬性'訂閱'undefinedpaho mqtt javascript客戶端無法訂閱主題

我在我的應用程序中包含了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) { 
 
    \t 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

這是一個範圍問題,'this'沒有指向你所想的'onConnect'當它回電話 – hardillb

回答

0

立即解決問題是可以解決的通過修改線

this.client.connect({onSuccess:this.onConnect.bind(this)}); 

,或者令人驚訝的你,通過移除所有this.clientmessage前提及

你應該知道在JavaScript中究竟意味着什麼this。與Java或C#中的不一樣。要了解清除工作的原因,請了解關閉和箭頭功能。

很好的起點(您的問題可以真正標記爲這一個副本): How to access the correct `this` context inside a callback?