When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code:
import { Component } from '@angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { Paho } from 'ng2-mqtt/mqttws31';
@Component({
selector: 'page-greywater',
templateUrl: 'greywater.html'
})
export class MQTT_Greenchain {
private _client: Paho.MQTT.Client;
private options = {
userName: 'rdjghvoh',
password: 'w7Ex0VTqZViw',
timeout: 30,
useSSL:true,
onSuccess:this.onConnected,
};
private topic: string;
public displayedMessage: string;
public mes: Paho.MQTT.Message;
public constructor() {
this._client = new Paho.MQTT.Client(
"m20.cloudmqtt.com",
Number(30775),
"",
"peter"
);
this._client.onConnectionLost = (responseObject: {errorCode: Number, errorMessage: string}) => {
console.log('poes');
console.log(responseObject.errorMessage);
};
this._client.onMessageArrived = (message: Paho.MQTT.Message) => {
this.onMessageArr(message);
console.log('Message arrived.');
};
this.topic = "haha";
this.displayedMessage = "what I was";
}
connectMe() {
console.log("MQTT OPTIONS: " + this.options);
this._client.connect(this.options);
}
private onConnected(): void {
console.log('Connected to broker.');
this._client.subscribe(this.topic);
this.mes = new Paho.MQTT.Message("-1"); // -1 => Notify
this.mes.destinationName = this.topic;
this._client.send(this.mes);
}
private onMessageArr(message: Paho.MQTT.Message){
this.displayedMessage = message.payloadString;
}
}
In Angular 1, I had no issues calling the following function and getting everything related to MQTT working. The Angular 1 function looks like this:
function onConnect() {
sharedUtils.hideLoading();
console.log("onConnect, CURRENT TOPIC: " + mqttData.currentTopic);
client.subscribe(mqttData.currentTopic);
}
The argument in the above function, mqttData.currentTopic
, is simply a string.
This function only accepts 1 argument even though it can technically accept 2 (an options object).
In Angular 2, TypeScript throws an error when I try to call the function with just one argument:
Supplied parameters do not match any signature of call target
Why does Angular 2 not allow me to call the function with only one argument as in Angular 1? When I provide {} as a second argument:
this._client.subscribe(this.topic, {});
I get the error:
AMQJS0005E Internal error. Error Message: Cannot read property 'subscribe' of undefined, Stack trace: TypeError: Cannot read property 'subscribe' of undefined
This error is received in the response object parameter passed to the onConnectionLost callback function.
Even though 'this._client' seems defined based on the console message 'Connected to broker.', where the onSuccess callback is evidently called, why am I encountering these issues?
What am I missing here?