How to use (mqtt) js library in angular 2 typescript app?

浪子不回头ぞ 提交于 2019-12-04 06:07:26

I did the following to get mine working:

1) first install ng2-mqtt via package.json in dependencies and run the npm update so that you have it in your node_modules

2) in your index.html, be sure to include it:

<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) Add the mqtts mapping, like so to systemjs.config.js(see map):

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

4) Import like you normally would:

import {Paho} from 'mqttws31'

5) use it in your @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); });

If all goes well, you should see your connection (assuming activemq): img

Refer to here for usage: https://github.com/icanos/ng2-mqtt

Nothing Work for me. in angular 8 i created code please Click Here to get that code. hope it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!