我有一個特定的問題。我正在試圖用typescript在angular2中實現mqtt.js庫。這裏是我的app.component.ts:Angular2 with Typescript - mqtt.js找不到客戶端
import { Component } from '@angular/core';
import * as mqtt from 'mqtt';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private client: mqtt.Client;
ngOnInit(): void {
this.connectToMQTTBroker();
}
public connectToMQTTBroker() {
console.log('trying to connect');
this.client = mqtt.connect('ws://mqttBroker.de:1882');
this.client.addListener('connect', this.on_connect);
this.client.addListener('message', this.on_message);
}
private on_connect() {
console.log('connected');
this.client.subscribe('/broker/response/clientID');
this.client.publish('/providers', '{...Message...}');
}
private on_message (args: any[]) {
console.log(args[0]);
console.log(args[1]);
}
}
它連接成功地,我在日誌中看到了「連接」的消息,但後來我得到Cannot read property 'subscribe' of undefined
爲什麼客戶端變量在on_connect方法不能訪問?我很確定我缺少一些基本的Typescript東西,但我無法弄清楚什麼。