带有Typescript的Angular2 - mqtt.js找不到客户端

时间:2017-04-21 12:35:44

标签: javascript angular typescript mqtt

我有一个具体的问题。我正在尝试使用typescript在angular2中实现mqtt.js库。这是我的app.component.ts:

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东西,但我无法弄清楚是什么。

2 个答案:

答案 0 :(得分:0)

你的问题是这个绑定(https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md)。 尝试替换

this.client.addListener('connect', this.on_connect);
this.client.addListener('message', this.on_message);

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

答案 1 :(得分:0)

您遇到的问题是this消息范围内的on_connect已发生变化。这与在回调函数中使用箭头符号时TypeScript如何处理this的赋值有关。将您的回叫绑定更新为以下内容:

this.client.addListener('connect', () => this.on_connect());
this.client.addListener('message', () => this.on_message());

在原始定义中不使用箭头符号TypeScript在处理Transpiles时不会处理范围绑定,因此this函数内的on_connect引用函数本身。