2017-04-21 37 views
0

我有一个特定的问题。我正在试图用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东西,但我无法弄清楚什么。

回答

0

,你正在运行到这个问题更换

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

尝试是thison_connect消息的范围内变化。这与在回调函数中如何使用箭头符号或不在回调函数中TypeScript如何处理this的分配有关。更新您回电绑定如下所示:

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

通过在您的原始定义打字稿不使用箭头符号不处理你的范围结合时,它Transpiles等等thison_connect函数内指函数本身。

相关问题