我正在尝试在连接到我的 MQTT 代理时执行一些操作,我在我的 ionic 2、Angular 2 应用程序中创建了一个 mqtt 提供程序,该提供程序如下:
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;
}
}
我已经能够毫无问题地在 Angular 1 中调用以下内容,并且我能够让与 MQTT 相关的所有内容正常工作。 Angular 1中的函数如下:
function onConnect() {
sharedUtils.hideLoading();
console.log("onConnect, CURRENT TOPIC: " + mqttData);
client.subscribe(mqttData.currentTopic);
}
在上面,mqttData.currentTopic
只是一个字符串。
该函数接受 1 个参数,尽管它可以接受 2 个参数(选项对象)。
在 Angular 2 中, typescript 给了我一个错误:
Supplied parameters do not match any signature of call target
为什么它不允许我像 Angular 1 中那样使用一个参数调用函数?如果我将其作为第二个参数:
this._client.subscribe(this.topic, {});
我收到的错误是:
AMQJS0005E Internal error. Error Message: Cannot read property 'subscribe' of undefined, Stack trace: TypeError: Cannot read property 'subscribe' of undefined
这是在响应对象参数中收到的错误,传递给 onConnectionLost 回调函数。
我非常确定我的“this._client”不是未定义的,因为消息“已连接到代理”。控制台出现,说明onConnected,connect方法的onSuccess属性回调明显被调用了?
我在这里没有得到什么?
最佳答案
试试这个,如果工作正常就回复
this.client.subscribe(this.topic, '');
关于javascript - 为什么在将 Paho MQTT 函数从 Angular 1 迁移到 Angular 2 时收到 typescript 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42723018/