0
votes

AMQJS0005E Internal error. Error Message: Cannot read property 'subscribe' of undefined

I included eclipse paho javascript client library in my app. connection is established but, I cannot subscribe to a topic. here is the code that I used..

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);
}
  
  

 

}
1
This is a scope problem, this does not point to what you think it does when in the onConnect callbackhardillb

1 Answers

1
votes

Your immediate problem is solvable by modifying the line

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

or, surprisingly for you, by removing all this. in front of client and message references.

You should learn what exactly means this in JavaScript. Not the same thing as in Java or C#. To understand why the removal works, learn about closures and arrow functions.

Good starting point (your question could be actually flagged as duplicate of this one): How to access the correct `this` context inside a callback?