1

I need to connect to multiple brokers from the same angular 6 app.

When importing MqttModule, we pass the config to it as:

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

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?

n00b_g33k
  • 1,111
  • 1
  • 6
  • 6

1 Answers1

3

I tried so many things but the only thing work for me is below (Angular 8)

install following command in your project

npm i buffer --save

npm i -S process

npm i mqtt --save

Add following line to polyfills.js at the end

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

import * as process from 'process';
window['process'] = process;

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()
    })
  }
}

Now Run your app using ng serve hope it's works

Community
  • 1
  • 1
Renish Gotecha
  • 2,232
  • 22
  • 21