问题描述
我需要从同一个angular 6应用程序连接到多个经纪人.
I need to connect to multiple brokers from the same angular 6 app.
在导入MqttModule时,我们将配置传递给它:
When importing MqttModule, we pass the config to it as:
imports: [...
MqttModule.forRoot(MQTT_SERVICE_OPTIONS),
...]
我尝试在相同的层次结构级别上创建2个单独的模块,并传递不同的配置并建立连接,但是它不起作用.
I tried creating 2 separate modules on same hierarchical level and passing different config and setting up the connections, but it is not working.
我认为它在根级别创建服务,我们不能在不同的模块中创建单独的连接.
I think it creates services at the root level and we cannot create a separate connection in different modules.
我们甚至可以创建多个连接吗?如果可以,怎么办?
Can we even create multiple connections? If so, how?
推荐答案
我尝试了很多事情,但对我来说唯一有效的方法是在以下位置(角度8)
I tried so many things but the only thing work for me is below (Angular 8)
在您的项目中安装以下命令
install following command in your project
npm i -S处理
npm i -S process
npm i mqtt-保存
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
add following code to your 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服务运行您的应用希望它能起作用
Now Run your app using ng servehope it's works
这篇关于如何使用ngx-mqtt库在angular 6中创建多个连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!