【问题标题】:How to create multiple connections in angular 6 using ngx-mqtt library?如何使用 ngx-mqtt 库在 Angular 6 中创建多个连接?
【发布时间】:2019-01-11 08:46:31
【问题描述】:

我需要从同一个 Angular 6 应用程序连接到多个代理。

在导入 MqttModule 时,我们将配置传递给它:

imports: [...
MqttModule.forRoot(MQTT_SERVICE_OPTIONS),
...]

我尝试在同一层级上创建 2 个单独的模块并传递不同的配置并设置连接,但它不起作用。

我认为它在根级别创建服务,我们无法在不同模块中创建单独的连接。

我们甚至可以创建多个连接吗?如果有,怎么做?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    我尝试了很多东西,但唯一对我有用的是下面(Angular 8)

    在您的项目中安装以下命令

    npm i 缓冲区 --save

    npm i -S 进程

    npm i mqtt --save

    将以下行添加到 polyfills.js 的末尾

    (window as any)['global'] = window;
    global.Buffer = global.Buffer || require('buffer').Buffer;
    
    import * as process from 'process';
    window['process'] = process;
    

    将以下代码添加到您的 app.component.ts

    import { Component } from '@angular/core';
    import * as mqttt from "mqtt";
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'checkMqttFromWeb';
      constructor(){
        var client = mqttt.connect('mqtt://192.168.0.29:1884')
        client.on('connect', function () {
          client.subscribe('fooBar', function (err) {
            if (!err) {
              client.publish('fooBar', 'Hello mqtt')
            }
          })
        })
    
        client.on('message', function (topic, message) {
          // message is Buffer
          console.log(message.toString())
          client.end()
        })
      }
    }
    

    现在使用 ng serve 运行您的应用 希望有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多