Guide to integrating the (mqtt) JavaScript library into your Angular 2 TypeScript application

I followed a similar approach as demonstrated in how-to-use-moment-js-library-in-angular-2-typescript-app but encountered the error message

error TS2307: Cannot find module 'mqtt'.

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

The above code did not find the typings, but this alternative method worked...

typings install mqtt --save --ambient 

This is how my tsconfig.conf is configured:

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

The content of ng2-mqtt.ts is simply...

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

And ./src/mqtt.service.ts includes...

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], typings 0.8.1, npm 2.14.20, node v4.4.1, Windows 7

Is it going to be challenging to integrate Angular 2 with external elements beyond its TypeScript ecosystem?

Answer №1

To successfully set up my system, I followed these steps:

1) Start by installing ng2-mqtt through package.json in dependencies and running npm update to ensure it is added to your node_modules.

2) Make sure to include it in your index.html file:

<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 in systemjs.config.js as shown below (under map):

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

4) Import Paho as you would normally do:

import {Paho} from 'mqttws31'

5) Use it within 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 everything works correctly, you should establish a connection (assuming activemq): img

For further usage guidance, visit: https://github.com/icanos/ng2-mqtt

Answer №2

I've been struggling to find a solution that works for me. I recently developed some code in Angular 8, so if you're facing similar issues, feel free to check out my code here. Hopefully, it helps you too!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine if a given date falls within the previous 24 hours using Javascript

In my javascript code, I have a date time provided in the format dd.MM.yyyy HH.mm. I want to verify if this date falls within the last 24 hours or not. For instance: If the current date and time is 06.04.2017 18:26 (dd.MM.yyyy HH.mm), the earliest permis ...

The code seems to be malfunctioning in a separate JS file, but oddly enough, it functions properly when placed within a <script> tag

I am trying to create a loader, but I have encountered an issue where the script works when placed directly in the HTML file, but not when it is in a separate JavaScript file. Here is the script: var loader = document.getElementById("ld"); w ...

What could be causing the Uncaught Error to persist even after using .catch()?

Check out this code snippet: function pause(ms:number) { return new Promise((resolve:any,reject:any) => setTimeout(resolve,ms)) } async function throwError(): Promise<void> { await pause(2000) console.log("error throw") throw new ...

Having trouble extracting the responseText from the Ajax request

My current challenge involves making an ajax call and receiving an Object in the response. However, when I attempt to access "responseText," it keeps returning as undefined: var results = API.get('users', { username: un, userpass: pw } ); conso ...

Why are polyfills-es2015, vendor-es2015, main-es2015, and other files blocked from loading because the MIME type is not allowed (text/html

Hey there! I've encountered an issue during the deployment of my Angular app. When I serve it from Angular locally, everything works perfectly fine. However, when I deploy it on a Tomcat server, I encounter errors and I can't see anything related ...

Why is Handlebars {{body}} not rendering my HTML tags properly?

I am perplexed by the fact that the example in the other file is not showing. While working on a CRUD project with Mongo, Express, and Node, I encountered an issue. The code wasn't functioning as expected, so I paused to figure out why. <!DOCTYPE ...

What causes TypeScript to convert a string literal union type to a string when it is assigned in an object literal?

I am a big fan of string literal union types in TypeScript. Recently, I encountered a situation where I expected the union type to be preserved. Let me illustrate with a simple example: let foo = false; const bar = foo ? 'foo' : 'bar' ...

"Exploring the world of Sharepoint Online WebParts with a touch

Recently, I decided to migrate a website that I previously built in SharePoint 2013 to be a Sharepoint Online WebPart. After doing some research, it seems like WebParts are typically created using TypeScript. Is TypeScript really the only way to go about b ...

The functionality of `npm run` does not meet the expected behavior within a Docker container

Currently, I am in the process of developing a React app using Vite and deploying it via Docker containers. However, when attempting to deploy the container, executing npm run build seems to have no effect; even manually running it inside the container doe ...

Ways to modify CSS using JavaScript

Can anyone assist me with a custom CSS code that I found? It looks like this: header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } I've been trying to change the color to #fff using JavaScript, but haven't had any success yet. ...

Issue: Angular controller fails to load during testing with Poltergeist/CapybaraExplanation: While conducting

Exploring the world of rails/angular for the first time has been an interesting journey. Currently, I am focusing on testing angular with poltergeist/capybara. While everything runs smoothly in the actual browser, it appears lifeless during testing. Despit ...

Ways to retrieve a variable from outside of a function

I am in need of sending the following batch data to the database, but I am facing difficulties in including the course_id along with the batchData. Currently, I am retrieving the course_id from another service that fetches data from a course table. I am ...

Node.js module mishap

In the package.json file I'm working with, these are the content of my dependencies: "devDependencies": { "chai": "^4.1.2", ... "truffle": "4.1.3" } A new NodeJS script called getWeb3Version.js was created: let web3 = require("web3" ...

Enhanced password encryption on the client side using jQuery ajax and PHP [advanced technique]

I found a solution here on how to encrypt data in javascript and decrypt it on the server side. I am encountering an issue while trying to implement this with my ajax form submission. I attempted to integrate it into my code snippet below, but it's no ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...

How to use the sha512 hash function in Node.js for Angular2 and Ionic2 applications

I'm attempting to generate a SHA512 Hash in Angular2 (Ionic2) that matches the PHP function hash('sha512'). After trying out different modules like crypto-js, crypto, and js-sha512, I keep getting a different Hash compared to PHP. I even a ...

"Generating a unique, random HEX color using JavaScript from an array

Currently, I am attempting to create a random border color within a div using specific hex codes that have already been determined, but I am encountering some difficulties. Does anyone have any suggestions on how to achieve this? I am still learning JavaS ...

Stop the repetition of event handlers by utilizing the .off() method to remove duplicates

Here's a scenario where I've assigned two event handlers: $('#myElement').on('click', '.classA', doSomething); $('#myElement').on('click', '.classB', doSomethingElse); Now, the task at ...

What could be causing the Angular error related to this HttpHeader?

Is there anyone who can assist me with why I am encountering an error in my Angular code while trying to use HttpHeaders to read the response status from the backend? Here is the specific error message: https://i.sstatic.net/tQu5t.jpg import { Injectable ...