2017-04-21 105 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函數內指函數本身。

相關問題