2016-05-03 75 views
5

我密切平行關係how-to-use-moment-js-library-in-angular-2-typescript-app採取的辦法,但仍然得到error TS2307: Cannot find module 'mqtt'.如何在角2打字稿應用程序中使用(mqtt)js庫?

npm install --save mqtt 
<s>typings install --save mqtt</s 

未找到分型但這並...

typings install mqtt --save --ambient 

我tsconfig.conf看起來像這樣

{ 
    "compilerOptions": { 
     "noImplicitAny": true, 
     "module": "commonjs", 
     "target": "ES5", 
     "emitDecoratorMetadata": true, 
     "experimentalDecorators": true, 
     "sourceMap": true, 
     "declaration": true 
    }, 
    "files": [ 
     "ng2-mqtt.ts" 
    ], 
    "exclude": [ 
     "node_modules" 
    ] 
} 

and ng2-mqtt.ts只是有這個...

export * from './src/mqtt.service' 

./src/mqtt.service.ts具有..

import {Injectable} from 'angular2/core'; 
import * as mqtt from 'mqtt'; 
@Injectable() 
export class MqttService { 
    constructor() { 
    //mqtt.connect('ws://10.0.1.100:3333') 
    // ... 
    } 
} 

TSC -version 1.8.10,[email protected],分型0.8.1,NPM 20年2月14日,節點v4.4.1, Windows 7

是不是會使用Angular 2與其類型腳本之外的元素太難了?

回答

2

我做了以下找我的工作:

1)首先通過的package.json在依賴安裝NG2,MQTT和運行NPM更新,以便您在node_modules

2)有它您的index.html,一定要包括它:

<html> 
<head> 
    <title>whatever</title> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 

    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css"> 
    <script>document.write('<base href="' + document.location + '" />');</script> 
    <script src="node_modules/ng2-mqtt/mqttws31.js" type="text/javascript"></script> 

3)添加mqtts映射,像這樣以systemjs.config.js(查看地圖):

System.config({ 
transpiler: 'typescript', 
typescriptOptions: {emitDecoratorMetadata: true}, 
map: { 
    '@angular': 'node_modules/@angular', 
    'mqttws31': 'node_modules/ng2-mqtt/mqttws31.js' 
}, 

4)導入像通常那樣:

import {Paho} from 'mqttws31' 

5)在@Component使用它:

this.client = new Paho.MQTT.Client("localhost", Number(61614), "myclientid_"); 

    this.client.onConnectionLost = (responseObject: Object) => { 
     console.log('Connection lost.'); 
     this.connected ="false"; 
     }; 

    this.client.onMessageArrived = (message: Paho.MQTT.Message) => { 
     console.log('Message arrived.'); 
     this.msg =message.payloadString; 
    }; 

    this.client.connect({ onSuccess: this.onConnected.bind(this); }); 

如果一切順利的話,你會看到你的連接(假設的ActiveMQ): img

請參考這裏用法: https://github.com/icanos/ng2-mqtt

相關問題