Angular2 with Typescript - mqtt.js找不到客户端
问题描述:
我有一个特定的问题。我正在试图用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东西,但我无法弄清楚什么。
答
你的问题是这个绑定(https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md)。 用
this.client.addListener('connect', this.on_connect.bind(this));
this.client.addListener('message', this.on_message.bind(this);
或
this.client.addListener('connect',() => {this.on_connect()});
this.client.addListener('message', (args) => {this.on_message(args)});
答
,你正在运行到这个问题更换
this.client.addListener('connect', this.on_connect);
this.client.addListener('message', this.on_message);
尝试是this
贵on_connect
消息的范围内变化。这与在回调函数中如何使用箭头符号或不在回调函数中TypeScript如何处理this
的分配有关。更新您回电绑定如下所示:
this.client.addListener('connect',() => this.on_connect());
this.client.addListener('message',() => this.on_message());
通过在您的原始定义打字稿不使用箭头符号不处理你的范围结合时,它Transpiles等等this
的on_connect
函数内指函数本身。